我有一个关于 CarrierWave 与模型关联交互的方式的快速问题——或者,在我的例子中,CarrierWave 没有的方式。我有一个模型,belongs_to
另一个模型,我想使用所有者的数据来设置 CarrierWavecache_dir
和store_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_id
andcontract_id
并调用Correction.new
those 和 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 的东西——无疑是一些愚蠢的东西,但我当然不确定。我毫不怀疑这最终会变得非常明显,但我会非常感谢任何人提出的任何建议。提前致谢!