After Create中的变量

时间:2011-05-23 06:46:31

标签: ruby-on-rails activerecord callback

我目前有以下内容:

class Question < ActiveRecord::Base
  belongs_to :product
  belongs_to :user
  belongs_to :asker, :class => "User", :foreign_key => "asker_id"
  has_one :track, :as => :trackable

  after_create :make_track

  def make_track
    create_track
  end
end

class Product < ActiveRecord::Base
  belongs_to :user
  has_many :questions
  has_one :track, :as => :trackable

  after_create :make_track

  def make_track
    create_track
  end
end

class Track < ActiveRecord::Base
  belongs_to :user
  belongs_to :trackable, :polymorphic => true
end

我想要做的是获取属于用户(用户)的曲目(曲目)以获得:

u = User.first
t = u.tracks

我试过投入:

  def make_track
    create_track(:user_id => :user)
  end

  def make_track
    create_track(:user_id => :user_id)
  end

但它没有帮助。如何在创建后插入保存当前问题/产品的用户的user_id?

以下mu之后的答案太短了。我得到了输出:

  SQL (0.1ms)   BEGIN
  Question Create (0.2ms)   INSERT INTO `questions` (`votes`, `created_at`, `asker_id`, `product_id`, `updated_at`, `question`) VALUES(0, '2011-05-23 07:55:25', 1, 1, '2011-05-23 07:55:25', 'the eight')
  Track Load (0.4ms)   SELECT * FROM `tracks` WHERE (`tracks`.trackable_id = 13 AND `tracks`.trackable_type = 'Question') LIMIT 1
  Track Columns (1.3ms)   SHOW FIELDS FROM `tracks`
  Track Create (0.3ms)   INSERT INTO `tracks` (`trackable_id`, `created_at`, `trackable_type`, `updated_at`, `user_id`) VALUES(13, '2011-05-23 07:55:25', 'Question', '2011-05-23 07:55:25', NULL)
  SQL (54.6ms)   COMMIT

我尝试在self.user中输出after_create,结果为nil

2 个答案:

答案 0 :(得分:1)

您只需在self上调用相应的访问者方法:

def make_track
  create_track(:user_id => self.user)
end

答案 1 :(得分:1)

您发布的SQL表明问题是用户没有在问题上设置(这就是传递给create_track时为零的原因)。

问题是否真的直接属于用户,还是属于用户通过产品?