我使用mongoID 2.0.2的Rails 3.0.6。最近我遇到了保存問題!方法時重寫setter(我想創建自己的嵌套屬性)。保存!在mongoid中引用屬性的方法
因此,這裏的模型:
class FeedItem
include Mongoid::Document
has_many :audio_refs
def audio_refs=(attributes_array, binding)
attributes_array.each do |attributes|
if attributes[:audio_track][:id]
self.audio_refs.build(:audio_track => AudioTrack.find(attributes[:audio_track][:id]))
elsif attributes[:audio_track][:file]
self.audio_refs.build(:audio_track => AudioTrack.new(:user_id => attributes[:audio_track][:user_id], :file => attributes[:audio_track][:file]))
end
end
if !binding
self.save!
end
end
AudioRef模型(這是剛剛audio_tracks和feed_items之間的緩衝液)是:
class AudioRef
include Mongoid::Document
belongs_to :feed_item
belongs_to :audio_track
end
而且AudioTrack:
class AudioTrack
include Mongoid::Document
has_many :audio_refs
mount_uploader :file, AudioUploader
end
所以在這裏是FeedItem模型的規格,它不起作用:
it "Should create audio_track and add audio_ref" do
@audio_track = Fabricate(:audio_track, :user_id => @author.id, :file => File.open("#{Rails.root}/spec/stuff/test.mp3"))
@feed_item= FeedItem.new(
:user => @author,
:message => {:body => Faker::Lorem.sentence(4)},
:audio_refs => [
{:audio_track => {:id => @audio_track.id}},
{:audio_track => {:user_id => @author.id, :file => File.open("#{Rails.root}/spec/stuff/test.mp3")}}
]
)
@feed_item.save!
@feed_item.reload
@feed_item.audio_refs.length.should be(2)
end
正如你可以看到,我重寫audio_refs的原因=方法是FeedItem可以從現有AudioTracks被創建(當存在PARAMS [:audio_track] [:ID]),或從上傳的文件(PARAMS [: audio_track] [:文件])。
問題是,當我運行此規範時,@ feed_item.audio_refs.length == 0,即audio_refs沒有保存。你能幫我解決嗎?
一番調查:
1)結合參數是由默認的「真」(這意味着我們在建設模式)
我建議你接受你以前的6個問題的答案 – 2011-06-15 13:16:02