按照我目前设置代码的方式,用户 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