0

背景:我有一個模型郵報「belongs_to的」用戶(我想使用post.user提取所發佈的創建者)和「的has_many,:用戶可以通過: :user_posts」(我想用post.users獲取不屬於創造者,但能夠有和屬於後用戶)通過回調的user_id設定爲對象

目的:目前,調用current_user.posts.create添加到CURRENT_USER post.users,而post.user仍然爲零。

我知道我可以簡單地做這個current_user.posts.create(user_id: current_user.id),但有沒有辦法自動設置user_id而不必每次都明確設置它? (?也許通過回調模型)

+0

在Rails 4,我可以在控制檯中運行:'用戶.first.posts.create(content:「my content」)'and get:'=>#<發佈ID:1,user_id:1,內容:「我的內容」,created_at:「2014-02-26 20:12 :16「,updated_at:」2014-02-26 20:12:16「>'。我稍後會在GitHub中發佈示例代碼,但是可以粘貼模型,也許可以遷移? – raviolicode

回答

0

我發現和你聲明協會爲了讓這裏的區別:

class Post < ActiveRecord::Base 
    belongs_to :user 
    has_many :user_posts, dependent: :destroy 
    has_many :users, through: :user_posts 
end 

current_user.posts.create #=> Link with user_id: nil 

class Post < ActiveRecord::Base 
    has_many :user_posts, dependent: :destroy 
    has_many :users, through: :user_posts 
    belongs_to :user 
end 

current_user.posts.create #=> Link with user_id: 1 
+0

我想你只需要'has_many:posts,通過::user_posts',這不是必須的'has_many:posts'。請參閱[Rails指南]中的示例(http://edgeguides.rubyonrails.org/association_basics.html#the-has-many-through-association)。可能它有兩個讓你意想不到的行爲。 – raviolicode

+0

對不起!我發佈了錯誤的模型代碼 - 我的意思是顯示Post,而不是User。更新以反映。 – neon