加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby on Rails – Paperclip和动态参数

发布时间:2020-12-16 19:28:10 所属栏目:百科 来源:网络整理
导读:我正在使用Paperclip为 Ruby on Rails编写一些图像上传代码,我有一个可行的解决方案,但它非常hacky所以我真的很感激如何更好地实现它的建议.我有一个’资产’类,其中包含有关上传图像的信息,包括Paperclip附件,以及封装尺寸信息的’Generator’类.每个“项目
我正在使用Paperclip为 Ruby on Rails编写一些图像上传代码,我有一个可行的解决方案,但它非常hacky所以我真的很感激如何更好地实现它的建议.我有一个’资产’类,其中包含有关上传图像的信息,包括Paperclip附件,以及封装尺寸信息的’Generator’类.每个“项目”都有多个资产和发电机;所有资产应根据每台发电机规定的尺寸调整大小;因此,每个项目都有一定的规模,其所有资产都应具备.

发电机型号:

class Generator < ActiveRecord::Base
  attr_accessible :height,:width

  belongs_to :project

  def sym
    "#{self.width}x#{self.height}".to_sym
  end
end

资产模型:

class Asset < ActiveRecord::Base
  attr_accessible :filename,:image # etc.
  attr_accessor :generators

  has_attached_file :image,:styles => lambda { |a| a.instance.styles }

  belongs_to :project

  # this is utterly horrendous
  def styles
    s = {}
    if @generators == nil
      @generators = self.project.generators
    end

    @generators.each do |g|
      s[g.sym] = "#{g.width}x#{g.height}"
    end
    s
  end
end

资产控制器创建方法:

def create
    @project = Project.find(params[:project_id])
    @asset = Asset.new
    @asset.generators = @project.generators
    @asset.update_attributes(params[:asset])
    @asset.project = @project
    @asset.uploaded_by = current_user

    respond_to do |format|
      if @asset.save_(current_user)
        @project.last_asset = @asset
        @project.save

        format.html { redirect_to project_asset_url(@asset.project,@asset),notice: 'Asset was successfully created.' }
        format.json { render json: @asset,status: :created,location: @asset }
      else
        format.html { render action: "new" }
        format.json { render json: @asset.errors,status: :unprocessable_entity }
      end
    end
  end

我遇到的问题是鸡蛋问题:新创建的Asset不知道在正确实例化之后要使用哪些生成器(大小规范).我尝试使用@ project.assets.build,但是在资产获得项目关联集之前,Paperclip代码仍然执行,并且在我身上没有.

‘if @generators == nil’hack是这样的,更新方法将在没有进一步黑客攻击的情况下工作.

总而言之,它感觉非常糟糕.任何人都可以建议如何以更明智的方式写这个,甚至是采取这种方式的方法吗?

提前致谢!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读