开发者

Rails nested form new association

I am currently creating a form with some nested attributes. The relevant parts are that there is a Sale model (the master model for the form), a Vehicle model (sale has_one vehicle and vehicle belongs_to sale), and a Registration_number model (many to many with vehicles, through an assignment table).

I am using the excellent Flexbox JQuery plugin, which allows an existing item to be selected or a new i开发者_运维问答tem to be created.

Because I am working with Flexbox, the fields in question are being coded largely in html, bypassing the rails helpers.

When I attempt to create a new registration number (using the field name sale[vehicle_attributes][registration_numbers_attributes][0][number]), everything works great, a new registration number is created and it is assigned to the vehicle. When I try to assign an existing registration number (using the field name sale[vehicle_attributes][registration_numbers_attributes][id]), however, I get the following error:

Couldn't find RegistrationNumber with ID=3 for Vehicle with ID=5

This doesn't seem to make a lot of sense - the way I see it, Rails should be trying to create this association, not find an existing association? Any ideas what I might be doing wrong?

Thanks!


You could achieve this by manipulating the intermediate table, here assignment.

Insert in your model:

accepts_nested_attributes_for :assignments

And in your html, append this line:

<input name="sale[vehicle_attributes][assignments_attributes][0][registration_number_id]" value="the_registration_number_id_goes_here" type="hidden">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜