更新未在嵌套模型中传播



>我有一个嵌套模型集:

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" } }

这导致对事件控制器#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

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:选项)

如果您只想测试标签属性是否已更新,为什么不尝试仅在该字段而不是整个"事件"上执行update_attribute呢?像这样:

@event.place_attributes.update_attribute(
      :label => params[:event][:place_attributes][:label]
)

未经测试 - 但你明白了...

已解决

为了更新嵌套模型,我需要添加模型实例 ID:

 put :update, :locale => I18n.locale, :id => @event_0[:id], :event => { :place_attributes => { id: @event_0.place[:id],  label: "a very beautiful place"} }

所以在:p lace_attributes中,我添加了现有的@event_0.place[:id],现在正在更新

我在 2 月 17 日 17:04 的 Anson 回答中找到了它,底部页面在accepts_nested_attributes_for find_or_create?

最新更新