简体   繁体   中英

Do I need a class variable or an instance variable?

I currently have an ActiveRecord model 'Team' with a column called owner_id .

The owner_id data is just temporary and will be redundant once after_create is called.

I want to drop the 'owner_id' column and tidy this up, but keep the functionality working. How can I do this?

For background:

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

You should be able to add an attr_accessor and continue assigning the owner_id attribute without a db column eg Team.new(:owner_id => 7)

class Team < ActiveRecord::Base
  attr_accessor :owner_id
end

You can also avoid explicitly assigning team_id if you'd like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM