2013-06-05 67 views
0

我有三個模型之間關聯:User,Post,Comment。評論是Post的嵌套資源。嵌套資源和建立聯繫的方法

的routes.rb

resources :posts do 
resources :comments 
end 

用戶模式:

has_many :comments 

Post模型:

has_many :comments 

評價模型:

belonsg_to :user 
belonsg_to :post 

目標是當用戶創建新評論時,它創建與該用戶的關聯。所以你可以看到它像用戶知道他所做的所有評論。

comments_controller.rb

def create 
    @post = Post.find(params[post_id] 
    @comment = @post.comments.build[:comment] 
    current_user.comments >> @comment 
    .... 
end 

new.html.erb

<% form_for [@post, @post.comment.build] do |f| %> 
..... 
<% end %> 

這給了我一個錯誤都沒法評論。我應該做些什麼來避免這種情況?

+0

什麼是程序模型?並且它'belongs_to'不是'belons_to' – hrr

+0

請參考此鏈接http://guides.rubyonrails.org/getting_started.html – visnu

+0

您犯了一個錯字,這可能是您的問題嗎?你寫了<%form_for [@post,@ post.comment.build] do | f | %>'而不是'

'。所以'comment'而不是'comment'。 – Arjan

回答

1

最有可能你缺少 「S」 字母。應該是評論:

<% form_for [@post, @post.comments.build] do |f| %> 
    ..... 
<% end %> 

如果有更多的邏輯背後你沒有發佈讓我們知道。你的創建行爲看起來很好。嘗試查看控制檯的student_id屬性,如果它的ID填充比你fine.cheers。

0

new.html.erb文件,您正在使用「s」作爲構建方法。

它應該是,在new.html.erb

<% form_for [@post, @post.comments.build] do |f| %> 
..... 
<% end %>