0

私が現在コードを設定している方法では、ユーザーはhas_many current_treatmentsを持っています(これは、それらとユーザーの間の関連付けでブール値の「current」がtrueに設定されているという点で他の処理とは異なります)。私が抱えている問題は、accepts_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)

has_many宣言で指定されているように、「現在の」ブール値をtrueに設定せずに、新しい処理が保存されることに注意してください。

編集:これが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を使用しても、accepts_nested_attributesによって生成されたメソッドが呼び出されることはありません。IDは、「user[current_treatment_attributes][]」の範囲である必要があります。

しかし、それでは、実際に:current_treatmentのaccept_nested_attributes_forを使用するのか、それとも:userと:current_treatmentの間のASSOCIATION(別名:current_treating)を使用するのかという疑問が生じます。Accepts_nested_attributes_forは、私が理解しているように、新しいオブジェクトを作成するように設計されています。私はここで新しい治療法を作成しようとしているのではなく、新しい治療法(別名、2つの間の関連)を作成しようとしています。

とにかく、少し自分自身に話しかけますが、この質問の私の希望する方向は、私が望んでいたほど鋭くないので、これを解決済みとしてマークします。

于 2011-01-15T23:26:09.240 に答える