【问题标题】:Link_to rails nested form editLink_to rails 嵌套表单编辑
【发布时间】:2012-08-20 19:41:37
【问题描述】:

我刚刚按照以下教程进行操作,效果很好。 http://www.communityguides.eu/articles/6

但有一点他对我来说很难,那就是编辑。

我调用了我的链接编辑已关注

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

然后将我带到一个错误的页面,不知道为什么。

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>

现在这里是 cmets 中的表单编辑

<%= 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 %>

这里是控制器 文章控制器展示

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

评论控制器编辑

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    看起来comment 是一个嵌套资源,因此您需要指定包含commentarticle。例如:

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

    comment_path 是一个未定义的方法,因为没有在顶层公开 cmets 的路由。运行rake routes 以查看可用的路线有时会有所帮助。

    更新:

    您链接的文章仅提供了 cmets 的 createdelete 操作。如果您需要支持编辑操作,则需要通过更改来修改路由:

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

    到:

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

    您还需要实现编辑和更新操作 - 按照惯例,编辑将显示表单,更新将处理表单提交。您还需要确保 @article 在您的编辑视图中可用。

    【讨论】:

    • 我已将comment/_form.html.erb 更改为
    • 我还做了一个 rake routes 并更改了 edit_article_comment_path 并删除了 _path,现在在查看我的文章时出现错误。它嵌套在@article 中,我从路由导轨和指南社区中阅读了很多内容,我错过了什么吗?
    • edit_article_comment_path 是正确的。我不确定您现在遇到了什么错误,但我已经用其他一些建议更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 2016-04-19
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多