0

这里是模型

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"]}}

我遇到的问题是位置。当我这样做时,regular_user 总是正确的

@user.update_attributes(params[:user])  

或者

@user = User.new(params[:user])
if @user.save

可能是因为它默认为 true....但是如果 role_ids > 3,我需要更改为 false

关于如何更改默认标志的任何想法

4

2 回答 2

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
于 2012-07-20T19:01:57.443 回答
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
于 2012-07-20T19:03:31.853 回答