1

さて、私は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_userする0かです。false

@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)

しかし、関連付けを設定するための標準はありますか?

4

1 に答える 1

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
于 2012-06-19T18:46:53.173 に答える