Link_to rails nested form edit

随声附和 提交于 2019-12-25 04:55:21

问题


I just followed the following tutorial and works great. http://www.communityguides.eu/articles/6

However one thing his hard for me and that is an edit.

I called my link_to edit has follow

<%= link_to 'Edit', edit_article_comment_path(@article, comment) %>

Which then bring me to a page with error and not sure why.

NoMethodError in Comments#edit

Showing /home/jean/rail/voyxe/app/views/comments/_form.html.erb where line #1 raised:

undefined method `comment_path' for #<#<Class:0xa8f2410>:0xb65924f8>
Extracted source (around line #1):

1: <%= form_for(@comment) do |f| %>
2:   <% if @comment.errors.any? %>
3:     <div id="error_explanation">
4:       <h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>

Now here the form in comments edit

<%= form_for(@comment) do |f| %>
  <% if @comment.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>

      <ul>
      <% @comment.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Here are the controller Article controller show

 @article = Article.find(params[:id])
 @comments = @article.comments.find(:all, :order => 'created_at DESC')

Comment controller edit

  def edit
    @comment = Comment.find(params[:id])
  end

回答1:


Looks like it comment is a nested resource so you need to specify the article in which the comment is contained. For example:

<%= form_for [@article, @comment] do |f| %>

comment_path is an undefined method because there is no route that exposes comments at the top-level. Its sometimes helpful to run rake routes to see what routes are available.

UPDATE:

The article you linked only provides create and delete actions for comments. If you need to support edit operations then you would need to modify the routes by changing:

resources :comments, :only => [:create, :destroy]  

to:

resources :comments, :only => [:create, :destroy, :edit, :update]  

You would also need to implement the edit and update actions - by convention edit will display the form and update will process the form submission. You will also need to make sure that @article is available in your edit view.



来源:https://stackoverflow.com/questions/12044042/link-to-rails-nested-form-edit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!