I have 2 models Product and Font. A product "has_many :fonts, :through => :product_available_fonts".
I have a javascript/jQuery UI that is creating a form to pass to rails to update these associations. From the UI, you can add an existing Font to a Product during configuration. You can also rearrange the order of the fonts. This order is stored as a field开发者_StackOverflow中文版 "order" in the ProductAvailableFont object that joins the Product and Font tables. Currently, Fonts are added through:
params[:product][:font_ids] = ["1","2","4"…]
and
@product.update_attributes(params[:product])
in the controller. Order is updated through
params[:product][:product_available_font_attributes] = [
{"id"=>"1", "order"=>"2"},
{"id"=>"2", "order"=>"1"}
]
The problem is that when the form is created, there is no ProductAvailableFont object for a Font that was just added to a Product. How can I define its order attribute when I don't have an ID for it?
First of all, I suggest changing the name of the join table to products_fonts (both words plural and leave our "available"). If I understand correctly it has a product_id, font_id and order field (and it's own id which you should never use).
When your user adds a font to a product (assuming the font already exists), your form/javascript/client should send a new order object to the server, with nested fonts_products attributes. Rails should deal with this automagically on the server side, if you've configured the model relations correctly.
To get the POST request right, most of the magic is done by rails' form builders. Are you trying to reproduce that with javascript? That might be tricky.
For anyone who runs into this, the conclusion that solved this issue in our code was to use only product[product_available_font_attributes][id][]
for all know ones, then product[product_available_font_attributes][font_id][]
for all know ones, followed by product[product_available_font_attributes][font_id][]
for all fonts to add. You have to make sure that you have the font_id element for all existing objects in the form after the id element and that they are in order, or else rails will mix them up.
精彩评论