私のアプリには、多くの目標を持つ連絡先があります (目標は連絡先に属します)。ネストされたフォームを使用して両方のモデルのデータを作成/更新しますが、作成/更新アクション中に最初の子ゴールのみが保存されます。これは、以下で渡されるパラメーターから確認できます。
Started PATCH "/contacts/2" for 127.0.0.1 at 2014-05-11 19:10:40 -0400
Processing by ContactsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wKgOPegIJOFyrrLAnbdD67qqATFXrPNqMIT7I/tpNfo=", "contact"=>{"name"=>"Steven Tyler", "title"=>"Manager", "company"=>"Dell", "email"=>"steve@dell.com", "notes"=>"cool guy", "goals_attributes"=>{"0"=>{"title"=>"goal1", "due_date(1i)"=>"2014", "due_date(2i)"=>"5", "due_date(3i)"=>"11", "notes"=>"fdfsd", "_destroy"=>"false", "id"=>"13"}}}, "commit"=>"submit", "id"=>"2"}
Contact Load (0.1ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = ? LIMIT 1 [["id", 2]]
(0.1ms) begin transaction
Goal Load (0.3ms) SELECT "goals".* FROM "goals" WHERE "goals"."contact_id" = ? AND "goals"."id" IN (13) [["contact_id", 2]]
(0.1ms) commit transaction
Redirected to http://localhost:3000/contacts/2
ここに私のモデルがあります:
class Contact < ActiveRecord::Base
belongs_to :user
has_many :goals, dependent: :destroy
accepts_nested_attributes_for :goals, allow_destroy: true, reject_if: lambda {|attributes| attributes['title'].blank? && attributes['notes'].blank?}
validates_presence_of :user_id,:name,:title,:email
end
class Goal < ActiveRecord::Base
belongs_to :contact
validates_presence_of :title, :due_date
end
また、連絡先コントローラーの強力なパラメーター:
def contact_params
params.require(:contact).permit(:name, :title, :company, :email, :notes, goals_attributes: [:title, :due_date, :notes, :contact_id, :_destroy, :id])
end
使用される 2 つのフォームは次のとおり です。助けてくれてありがとう。