1

我有一个关于 CarrierWave 与模型关联交互的方式的快速问题——或者,在我的例子中,CarrierWave 没有的方式。我有一个模型,belongs_to另一个模型,我想使用所有者的数据来设置 CarrierWavecache_dirstore_dir. 但是我发现当我调用类似的东西时model.other_model.attribute,我得到一个 NoMethodError 说 nil 类没有attribute

这已尽我所能翻译成语言;这是实际的代码:

# app/models/correction.rb
class Correction < ActiveRecord::Base
  belongs_to :submission, inverse_of: :corrections
  belongs_to :contract, inverse_of: :corrections

  mount_uploader :pdf, CorrectionsUploader
end

# app/models/contract.rb
class Contract < ActiveRecord::Base
  belongs_to :author, inverse_of: :contracts
  belongs_to :submission, inverse_of: :contract
  has_many :corrections, inverse_of: :contract

  mount_uploader :pdf, ContractUploader
end

# app/uploaders/corrections_uploader.rb
class CorrectionsUploader < FogCorrectionsUploader
  include ::CarrierWave::Backgrounder::Delay
  include CarrierWave::RMagick
  include CarrierWave::MimeTypes

  storage :fog

  def store_dir
    "corrections/#{model.contract.legal_name}/#{model.contract.titles}"
  end

  def cache_dir
    "/www/website.com/_www/shared/submissions/corrections/#{model.contract.legal_name}/#{model.contract.titles}"
  end

  def extension_white_list
    %w(pdf)
  end
  # ...some processing directives that don't seem relevant...
end

控制器从表单中获取一个submission_idandcontract_id并调用Correction.newthose 和 other correction_params,正如您所期望的那样触发 CarrierWave,然后由于model.contract.

由于 ORM 对我来说仍然是一片黑暗的大陆,因此我尝试启动 Rails 控制台并执行此操作,但没有遇到任何问题:

2.0.0 :002 > test_correction = Correction.new({contract_id: 18, submission_id: 161})
    => #<Correction id: nil, submission_id: 161, contract_id: 18, pdf: nil, created_at: nil, updated_at: nil, comment: nil, delivered: nil>
2.0.0 :003 > test_correction.submission
    D, [2013-10-12T21:14:31.352684 #1758] DEBUG -- :   Submission Load (15.3ms)  SELECT "submissions".* FROM "submissions" WHERE "submissions"."id" = $1 ORDER BY "submissions"."id" ASC LIMIT 1  [["id", 161]]
    => #<Submission id: 161, title: ...>

所以看起来我错过了一些关于 CarrierWave 的东西——无疑是一些愚蠢的东西,但我当然不确定。我毫不怀疑这最终会变得非常明显,但我会非常感谢任何人提出的任何建议。提前致谢!

4

1 回答 1

0

万一其他有类似问题的人遇到这个问题,我发现问题出在我的表格上。我将hidden_fields放在表单的最后contract_id,在上传按钮之后,以及在强参数调用的最后。显然是绊倒了它,因为 Rails 试图按照接收参数的顺序处理参数,并且在它为and分配值之前就到达了上传者。submission_idpermit()contract_idsubmission_id

于 2013-10-13T12:28:08.813 回答