Generating a model with many to many in Ruby on Rails

泄露秘密 提交于 2019-12-03 10:50:45
Hitham S. AlQadheeb

Remember that you do not want an id for the join table, so make sure to add :id => false |t|

create_table assemblies_parts, :id => false do |t|
  t.integer :assembly_id
  t.integer :part_id
end

If you use rails

rails generate model Assemblies_parts assembly:references part:references

you will have two indexes, but what you want is

# Add table index
add_index :assemblies_parts, [:assembly_id, :part_id], :unique => true

UPDATE

You can use this reference from the Rails Guides.Here is the link. Also you will need to manually create the join table for those models using a migration.

e.g

    create_table :assemblies_parts, :force => true do |t|
      t.integer :assembly_id
      t.integer :part_id
    end
akrisanov

Please look at this question first: Creating a many-to-many relationship in Rails 3.

In addition, I would recommend next book "Ruby on Rails 3 Tutorial: Learn Rails by Example" for a better understanding of ActiveRecord relations.

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