我需要一个类变量还是一个实例变量?

时间:2014-03-04 22:20:20

标签: ruby-on-rails activerecord

我目前有一个ActiveRecord模型'Team',其中包含一个名为owner_id的列。

owner_id数据只是暂时的,一旦调用after_create就会多余。

我想删除'owner_id'列并整理它,但保持功能正常。我怎么能这样做?

背景:

class Team < ActiveRecord::Base
  attr_accessible :name, :owner_id, :team_id
  has_many :team_memberships, :dependent => :destroy
  has_many :users, through: :team_memberships
  accepts_nested_attributes_for :team_memberships

  after_create :create_team_membership

  private

  def create_team_membership
    TeamMembership.create(
      :user_id => self.owner_id,
      :team_id => self.id,
      :roles => "site_admin")
  end
end

1 个答案:

答案 0 :(得分:0)

您应该能够添加attr_accessor并继续分配owner_id属性而不使用数据库列,例如Team.new(:owner_id => 7)

class Team < ActiveRecord::Base
  attr_accessor :owner_id
end

如果您愿意,也可以避免明确指定team_id

class Team < ActiveRecord::Base
  def create_team_membership
    team_memberships.create(:user_id => owner_id, :roles => "site_admin")
  end
end