Does accepts_nested_attributes_for obey the conditions in a has_many declaration?
With the way I currently have my code set up, a user has_many current_treatments (which are distinct from other treatments in that the association between them and user has a boolean "current" set to true). The problem I am having is that when I try to specify a user's current treatments in a nested form via accepts_nested_attributes_for, the "treatings" are not being saved with the "current" boolean set.
I had assumed accepts_nested_attributes_for does this work for you. Does it not? If it does, what am I doing wrong? If it does not, what is the best practice manner of achieving this?
Here's my开发者_Go百科 example:
# 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
And I'm trying to allow the user to set his current treatments via:
# 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/>
But upon submission of the form, I get something like:
# 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)
Note that the new treating is saved without the "current" boolean set to true as specified in the has_many declaration.
EDIT: Here is the Treatment
model.
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
Well I found out the obvious problem myself:
# 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/>
Using a select_tag by id "user[current_treatment_ids][]" is never going to call the method generated by accepts_nested_attributes for. The id would need to be something to the extent of "user[current_treatment_attributes][]".
But then I think that raises the question of whether I actually want to accept_nested_attributes_for :current_treatment or, instead, the ASSOCIATION between :user and :current_treatment aka what might be called :current_treating. Accepts_nested_attributes_for, as I understand is designed to create new objects. I'm not trying to create new treatments here, just new treatings (aka associations between the two).
Anyway, talking to myself a bit, but I'm going to mark this as resolved, since my desired direction of this question is no longer as sharp as I had hoped.
精彩评论