2015-02-23 26 views
0

我試圖創建一個博客,我有3個模型post,user,comment。當我創建comment時,comment.post_idnil。我究竟做錯了什麼?爲什麼user_id未分配comment_id?

comments_controller

def new 
    @comment = Comment.new 
    end 

    def edit 
    @post = Post.find(params[:post_id]) 
    end 

    def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.create(comment_params) 
    @comment.user_id = current_user 
    redirect_to post_path(@post) 
    end 

編輯

post.rb

has_many :comments, dependent: :destroy 
    belongs_to :user 

comment.rb

belongs_to :user 
    belongs_to :post 

user.rb

has_many :posts, dependent: :destroy 

    has_many :comments, dependent: :destroy 
+0

在這些模型中顯示您的關聯。 – 2015-02-23 17:00:47

+0

更新後的問題 – vveare138 2015-02-23 17:03:49

回答

0

這裏是溶液:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.new(params[:comment]) 
    @comment.user_id = current_user.id 
    @comment.save 
    redirect_to post_path(@post) 
end 

來源:Answer in stackoverflow

所以,使用以下關聯如上源。

+0

是的,它會工作。只有'@comment.user = current.user' – vveare138 2015-02-23 17:37:41

0

希望這會起作用。

def create 
    @post = Post.find(params[:post_id]) 
    @comment = Comment.new(comment_params.merge(user_id: current_user.id)) 
    @post.comments << @comment 
    redirect_to post_path(@post) 
end