2016-07-10 62 views
0

我尝试使用Ruby on Rails创建关联类,但它不起作用。Rails关联类

我需要这样做:

enter image description here

我创造我模型,但我不知道我这样做是在这里

有人可以从一开始给我解释一下?

class CreateJobsUsers < ActiveRecord::Migration 
    def change 
    create_table :jobs_users, id: false do |t| 
     t.belongs_to :jobs, index: true 
     t.belongs_to :users, index: true 
     t.integer :level 
    end 
    end 
end 

回答

0

这是关系many to many,你可以这样做:

class User < ApplicationRecord 
    has_many :user_jobs 
    has_many :jobs, through: :user_jobs 
end 

class UserJob < ApplicationRecord 
    belongs_to :user 
    belongs_to :job 
end 

class Job < ApplicationRecord 
    has_many :user_jobs 
    has_many :users, through: :user_jobs 
end 

详细了解有关many to many,你可以参考在:

association many to many

+0

好的谢谢你,我修改我的帖子能你告诉我,如果我的迁移创建表具有良好的?我从来不知道我是否需要在创建表格时输入'S' –

+0

我假设你的迁移文件应该包含如下单数形式:t.belongs_to:job,index:true和t.belongs_to:user,index:true。有关更多详细信息,可以查看关联的Rails指南,第2.4节has_many:通过关联。链接:http://guides.rubyonrails.org/association_basics.html – Maxo