我有一个嵌套模型集:
class Event < ActiveRecord::Base
belongs_to :place
:place
attr_accessible :place_attributes, :reject_if => :all_blank, :allow_destroy => false
class Place < ActiveRecord::Base
has_many :events
validates :label, :presence => true,
:uniqueness => {:case_sensitive => true, :on => :create }
validates :description, :presence => {:on => :create},
:uniqueness => {:case_sensitive => true , :on => :create}
在测试场景中,使用嵌套表单,用户只能更新Place#label属性,并保留所有其他信息。
test "should_update_event_place_data" do
put :update, :locale => I18n.locale, :id => @event[:id],
:event => { :place_attributes => { label: "a very beautiful place" } }
导致对EventsController#update的请求,接收参数:
params
{"event"=>{"place_attributes"=>{"label"=>"a very beautiful place"}}, "locale"=>"en",
"id"=>"145", "controller"=>"backoffice/events", "action"=>"update"}
(rdb:1) @event.update_attributes(params[:event])
false
@messages={:"place.description"=>["cannot be blank"]
但是验证是在创建,而不是更新....应该检测不到验证错误.. 什么可能是错的?
感谢您的帮助
I did more testing
debugger , right after the test setup ( before sending the put request)
@event_0
#<Event id: 161, account_id: 3, place_id: 249, slug: "my-new-event-on-2013-01-01-at- edinburgh-united-king...", title: "My New Event"
@event_0.place
#<Place id: 249, label: "new fake place",..
test request:
put :update, :locale => I18n.locale, :id => @event_0[:id], :event => { :place_attributes => { label: "a very beautiful place"} }
params in request are OK, @request/method = PUT
In EventsController#update
@event.update_attributes(params[:event])
.... I inserted a debug in the Place model...
(before_validation :i_am_on_create, :on => :create)
def i_am_on_create
debugger
p "CREATING"
end
and it's creating !! don't understand why it's not updating the parent nested model
答案 0 :(得分:1)
update_attributes不会将更新传播到关联。如果你看源代码(http://apidock.com/rails/ActiveRecord/Base/update_attributes),你会看到#save 最后被称为。这是默认行为:
# existing resource 'mazeratti car'
car.name = "Wheelz"
car.brand.label = "Ferrari"
car.save
car.reload
car.name #=> "Wheelz"
car.brand.label #=> "Mazeratti"
如果您希望在更新对象时始终更新关联,请查看使用“自动保存”(http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/belongs_to:Options)
答案 1 :(得分:0)
如果您只想测试标签属性是否已更新,为什么不尝试仅对该字段执行update_attribute而不是整个事件&#39;?类似的东西:
@event.place_attributes.update_attribute(
:label => params[:event][:place_attributes][:label]
)
未经测试 - 但你明白了......
答案 2 :(得分:0)
解决
为了更新嵌套模型,我需要添加模型实例id:
put :update, :locale => I18n.locale, :id => @event_0[:id], :event => { :place_attributes => { id: @event_0.place[:id], label: "a very beautiful place"} }
所以在:place_attributes中,我添加了现有的@ event_0.place [:id],现在正在更新
我在2月17日下午17点04分在Anson的答案中找到了它 accepts_nested_attributes_for with find_or_create?