有没有办法在连接表中设置额外的值

时间:2012-06-19 18:33:23

标签: ruby-on-rails ruby-on-rails-3

好的,所以我在Rails中有这种关系:

class Position < ActiveRecord::Base
  belongs_to :company
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :companies, :through => :positions
  has_many :positions

class Company < ActiveRecord::Base
  has_many :positions
  has_many :users, :through => :positions

以下是职位架构:

create_table "positions", :force => true do |t|
  t.integer  "company_id"
  t.integer  "user_id"
  t.datetime "created_at",                     :null => false
  t.datetime "updated_at",                     :null => false
  t.boolean  "regular_user", :default => true
end

regular_user正在向管理员和员工发出信号,因此我的问题是如何根据此数据设置regular_user0false

@user = User.find(params[:user_id])
@company = Company.find(params[:company_id])
@user.companies << @company

有更好的方法吗?我在想:

Position.create(user_id: params[:user_id], company_id: params[:company_id], regular_user: 0)

但是有没有设置关联的标准?

1 个答案:

答案 0 :(得分:2)

试试这个:

class User < ActiveRecord::Base
  has_many :positions
  has_many :companies, :through => :positions
  has_many :companies_as_non_regular_user, :through => :positions, 
           :conditions => {:"positions.regular_user" => false}
  ...
end

@user = User.find(params[:user_id])
@company = Company.find(params[:company_id])
@user.companies_as_non_regular_user << @company