嵌套的部分表单编辑Link_to Rails

时间:2013-09-24 13:17:36

标签: ruby-on-rails ruby-on-rails-3 link-to form-for

我一直盯着这几个小时,我知道这只是一个小小的错误,但我还不知道看到它。

我使用此网站创建了博客的第一部分,过去3小时我一直在尝试添加编辑链接,以便用户可以编辑评论并进行更新。

http://www.reinteractive.net/posts/32

让编码开始:

图书模型

class Book < ActiveRecord::Base
  attr_accessible :title
  validates_presence_of :title
  has_many :snippets
  belongs_to :user
  accepts_nested_attributes_for :snippets
end

摘录(评论)模型

 class Snippet < ActiveRecord::Base
   belongs_to :book
   belongs_to :user
   attr_accessible :body, :user_id
 end

代码段控制器

class SnippetsController < ApplicationController   
  before_filter :authenticate_user!, only: [:create]

  def create
    @book = Book.find(params[:book_id])
    @snippet = @book.snippets.create!(params[:snippet])
    redirect_to @book
  end      

  def edit
    @snippet = Snippet.find(params[:book_id])
  end        

  def show
    @book = Book.find(params[:id])
    @snippet = @book.comments.find(:all, :order => 'created_at DESC')
  end    
end

Snippet _form.html.erb

<% form_for([@book, @snippet], :url => edit_book_snippet_path(@book)) %>
  <%= form.error_notification %>

  <div class="form-inputs">
    <%= f.input :title %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>

这就是为什么当我看到我得到的rake路线时我无法理解:

  

edit_book_snippet GET /books/:book_id/snippets/:id/edit(.:format)   片断#编辑

我的路线是这个

> http://localhost:3000/books/3/snippets/12/edit

但我的错误仍然是这样:

  

路由错误

     

没有路由匹配{:action =&gt;“edit”,:controller =&gt;“snippets”,   :book_id =&GT;零}

开始从树屋学习铁路,但是中级和喜欢学习更难(但更有趣)的方式。

非常感谢。

2 个答案:

答案 0 :(得分:0)

我认为这不起作用,因为在edit行动中你有以下

@snippet = Snippet.find(params[:book_id])

但是在您的_form部分中,您致电@book

<% form_for([@book, @snippet], :url => edit_book_snippet_path(@book)) %>

在任何情况下edit_book_snippet_path(@book)都是错误的,因为您应该提供所需的ID,因为路线要求

books/**:book_id/snippets/**:id/edit

最好这样写一下(尽管你也可以为before_filter和/或@book的身份验证用户创建一个@snippet,因为你可能会使用它们在这个控制器很多)

snippet_controller.rb

def edit
  @book = Book.find(params[:id]) 
  @snippet = Book.snippets.find(params[:book_id])
end  

_form.html.erb

<% form_for([@book, @snippet], :url => edit_book_snippet_path(book_id: @book.id, id: @snippet.id)) %>

答案 1 :(得分:0)

您忘记在控制器的edit操作中指定该书,并且由于您需要在控制器的多个操作中使用该书,因此您可以创建before_filter回调以使您的代码更干。

例如:

class SnippetsController < ApplicationController   
  before_filter :authenticate_user!, only: [:create]
  before_filter :find_book

  def create
    @snippet = @book.snippets.create!(params[:snippet])
    redirect_to @book
  end      

  def edit
    @snippet = Snippet.find(params[:id])
  end        

  private

  def find_book
    @book = Book.find(params[:book_id])
  end
end

我删除了控制器的show操作,因为它应该用于显示一个代码段,而不是一本书的所有代码段。为此,您可以使用index的{​​{1}}操作,或更好地使用SnippetsController的{​​{1}}操作。

最后一件事,你在表单声明中使用的url是错误的,因为你需要同时指定book和snippet:

show

要获得使用Rails创建博客的基础,我建议您阅读经典Rails guide