0

按照我目前设置代码的方式,用户 has_many current_treatments (与其他治疗不同,它们与用户之间的关联将布尔“当前”设置为 true)。我遇到的问题是,当我尝试通过 accept_nested_attributes_for 以嵌套形式指定用户的当前治疗时,“治疗”没有与“当前”布尔集一起保存。

我假设accepts_nested_attributes_for 为你工作。不是吗?如果是这样,我做错了什么?如果没有,实现这一目标的最佳实践方式是什么?

这是我的例子:

 # user.rb
  has_many :treatings
  has_many :treatments, :through => :treatings
  has_many :current_treatments, :through => :treatings, :conditions => {'treatings.current' => true}, :source => :treatment

  accepts_nested_attributes_for :current_treatments

我试图让用户通过以下方式设置他当前的治疗方法:

 # user/edit.html.erb
  <%= select_tag "user[current_treatment_ids][]", options_from_collection_for_select(Treatment.all, "id", "name", @user.current_treatment_ids), :multiple=>true %><br/>

但是在提交表格后,我得到如下信息:

 # development.log
  SQL (0.4ms)  INSERT INTO "treatings" ("created_at", "current", "treatment_id", "updated_at", "user_id") VALUES ('2011-01-15 18:49:02.141915', NULL, 4, '2011-01-15 18:49:02.141915', 1)

请注意,保存新处理时没有将“当前”布尔值设置为 true,如 has_many 声明中指定的那样。

编辑:这是Treatment模型。

class Treatment < ActiveRecord::Base

  has_many :treatings
  has_many :users, :through => :treatings
  has_many :current_users, :through => :treatings, :conditions => {:current => true}, :source => :user
  has_many :past_users, :through => :treatings, :conditions => {:current => false}, :source => :user

end
4

1 回答 1

1

好吧,我自己发现了明显的问题:

# user/edit.html.erb 
<%= select_tag "user[current_treatment_ids][]", options_from_collection_for_select(Treatment.all, "id", "name", @user.current_treatment_ids), :multiple=>true %><br/>

使用 id "user[current_treatment_ids][]" 的 select_tag 永远不会调用 accept_nested_attributes 生成的方法。id 需要达到“user[current_treatment_attributes][]”的程度。

但后来我认为这引发了一个问题,即我是否真的想接受_nested_attributes_for :current_treatment 或者相反,:user 和 :current_treatment 之间的关联,也就是可能称为​​ :current_treating 的关联。据我了解,Accepts_nested_attributes_for 旨在创建新对象。我不是想在这里创造新的治疗方法,只是新的治疗方法(也就是两者之间的关联)。

无论如何,和自己聊聊,但我将把它标记为已解决,因为我对这个问题的期望方向不再像我希望的那样尖锐。

于 2011-01-15T23:26:09.240 回答