How to save 2 id in joint table for many-to-many relationship in rails 3.1

这一生的挚爱 提交于 2019-12-11 11:55:56

问题


There are two models. One is rfq and another one is standard. It is like:

class Rfq << ActiveRecord::Base
  has_and_belongs_to_many :standards
end

class Standard << ActiveRecord::Base
  has_and_belongs_to_many :rfqs
end

Table rfqs_standards has been created. My question is when creating rfq, how to save the paid of rfq_id and standard_id in table rfqs_standards automatically.

Thought adding accepts_nested_attributes_for :standard in rfq model. However since there is no real attributes (but just pair of id) saved for this many-to-many relationship, this seems not the right way.

Both rfq and standard was declared in routes.rb as resources :rfqs and resources :standards.

The procedure is when creating rfq, standard will be picked up via a drop down list. Then rfq is saved and at the same time, a new entry in joint table is created. When creating new standard, there is no need to create entry in joint table.

Any suggestion to save the id in joint table? Thanks.


回答1:


this is easier than you might think because it's handled automatically by ActiveRecord.

When you say "has_and_belongs_to_many", you're telling AR to associate those two models with a many-to-many relationship using the table, and for the most part you no longer need to worry about the join table. When you add an instance of Standard to an Rfq's list of standards, this will be done for you.

Here's an example:

rfq = Rfq.create
standard = Standard.create
rfq.standards << standard

We've created each of the objects, and the third line creates the connection, saving a new record in the rfqs_standards table with the proper ids. rqf.standards looks and acts like a normal array, but when you assign objects to it, ActiveRecord does the database work for you.

After creating the records, you could have also done:

standard.rfqs << rfq

You could also do both at the same time:

rfq = Rfq.create
standard rfq.standards.create

This created an rfq, then created a standard that is automatically connected to the rfq. You can do the same thing in reverse:

standard = Standard.create
rfq = standard.rfqs.create

I hope this helps!

UPDATE: Since you mentioned forms and automatic saving, read my article on nested attributes that shows how to implement that, including full code samples.



来源:https://stackoverflow.com/questions/8736805/how-to-save-2-id-in-joint-table-for-many-to-many-relationship-in-rails-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!