目前,我有以下幾點:變量在創建後
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
我想要做的就是,爲了belongs_to的用戶(用戶)來獲得軌道(軌道):
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
我試着在after_create
輸出self.user
這就造成了nil
。
此更改後,Track中的user_id不包含任何內容。 – 2011-05-23 07:54:48
也許是因爲它所屬的模型也沒有設置user_id屬性? – taro 2011-05-23 08:07:35
我的模型中有關於user_id和asker_id的衝突。 – 2011-05-23 08:09:41