2014-02-11 25 views
0

我有一個看起來像這樣如何訪問rails中的雙重嵌套模型?

resources :questions do 
    resources :answers do 
     resources :comments 
    end 
end 

但是路線,當我嘗試建立一個評論

<%= form_for([@answer, @answer.comments.build]) do |f| %> 

<p> 
    <%= f.label :comment %> 
    <%= f.text_area :comment, :cols => "50", :rows => "30"%> 
</p> 
<p> 

我得到了一個未定義的方法的意見。這是我創建的評論看起來像

def create 
    @answer = Answer.find(params[:answer_id]) 
    @comment = @answer.comments.create(params[:comment]) 
     redirect_to question_path(@question) 
end 

並回答has_many評論和評論屬於答案。有任何想法嗎?謝謝!

+0

什麼ü有在你的控制器「新」行動 –

+0

沒有新的行動,因爲新評論的形式顯示在另一個視圖 – google1254

+0

你運行遷移嗎? – Danny

回答

0

您可以從您的應用程序的任何控制器的接入模式(只需調用Model.class_method


看你的代碼,我建議你做這樣的事情:

#app/views/answers/show.html.erb 
<% @answer.comments.each do |comment| %> 
    <%= comment.value %> 
<% end %> 

<%= form_for @new_comment do |f| %> 
    <%= f.text_area :comment, :cols => "50", :rows => "30"%> 
<% end %> 

#app/controllers/answers_controller.rb 
def new 
    @answer = Answer.find(params[:id]) 
    @new_comment = Comment.new 
end 


#app/controllers/comments_controller.rb 
def create 
    @comment = Comment.new(comment_params) 
    @comment.save 
end 

private 
def comment_params 
    params.require(:comment).permit(:your, :attributes, :here) 
end