我有一个关于CarrierWave与模型关联的交互方式的快速问题 - 或者,就我而言,CarrierWave没有的方式。我有一个belongs_to
另一个模型,我想使用所有者的数据来设置CarrierWave的cache_dir
和store_dir
。但我发现当我调用像model.other_model.attribute
这样的东西时,我得到一个NoMethodError,说nil类没有attribute
。
我最好能将其翻译成 language 语言;这是实际的代码:
# 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_id
和contract_id
,然后使用Correction.new
和其他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的东西---毫无疑问是愚蠢的,但我当然不确定。我毫不怀疑这会让人感到尴尬,但我真的非常感谢任何人的建议。提前谢谢!
答案 0 :(得分:0)
如果有其他类似麻烦的人遇到这种情况,我发现故障是我的形式。我已将hidden_field
和contract_id
放置在表单的 end ,上传按钮之后,以及最后一端的submission_id
-parameters permit()
来电。显然 正在绊倒它,因为Rails正在尝试按接收顺序处理参数,并且在为contract_id
和{{分配值之前它已进入上传器1}}。