以下是模型
class User < ActiveRecord::Base
has_many :companies, :through => :positions
has_many :positions
class Company < ActiveRecord::Base
has_many :positions
has_many :users, :through => :positions
class Position < ActiveRecord::Base
belongs_to :company
belongs_to :user
attr_accessible :company_id, :user_id, :regular_user
end
我的架构
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
我有这些参数
Parameters: {"user"=>{"id"=>"", "first_name"=>"some", "last_name"=>"name",
"phone_number"=>"4074615519", "email"=>"something@gmail.com", "active"=>"true",
"company_ids"=>["186"], "role_ids"=>["2"], "notification_ids"=>["1", "2", "3"]}}
我遇到的问题是position.regular_user在我做
时总是如此@user.update_attributes(params[:user])
或
@user = User.new(params[:user])
if @user.save
可能因为它默认为true ....但是如果role_ids是&gt;我需要更改为false。 3
有关如何更改默认标志的任何想法
答案 0 :(得分:0)
使用before_save
回调设置role_id
属性。例如:
class User
before_save :set_role_id
private
def set_role_id
if role_id > 3
self.regular_user = false
end
end
end
答案 1 :(得分:0)
使用before_save
过滤器:
class Position < ActiveRecord::Base
belongs_to :company
belongs_to :user
attr_accessible :company_id, :user_id, :regular_user
before_save :update_regular_flag
private
def update_regular_flag
self.regular_user = (role_id <= 3)
end
end