在我的应用程序中,我有联系人,其中有很多目标(目标属于联系人)。我使用嵌套表单为两个模型创建/更新数据,但是在创建/更新操作期间仅保存第一个子目标,这可以从下面传递的参数中看出:
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
以下是使用的两种形式: https ://gist.github.com/nowgeez/5fbe99e814330c1b371c 知道为什么只保存第一个目标,而没有在表格中创建任何其他后续目标吗?在此先感谢您的帮助。