0

我有一个嵌套模型集:

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
4

3 回答 3

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

于 2012-12-04T15:54:23.390 回答
0

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

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

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

于 2012-12-04T12:29:03.947 回答
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 在底页的 Accept_nested_attributes_for 和 find_or_create 的 Anson 回答中找到了它?

于 2012-12-04T15:51:41.870 回答