开发者

Rails 3.1: Upgrading caused my link_to path routes to break?

I have some routes that worked fine in my Rails 3.0.7 app prior to upgrading to 3.1.

# routes.rb
resources :chapters do
  resources :cards
end

resources :cards

With some controller code like this:

  def show
    @book = Book.find(params[:book_id])
    @chapter = Chapter.find(params[:id])
    @card =开发者_运维知识库 @chapter.cards.new   # for "new card" form thats displayed on this same page
    respond_with(@chapter)
  end

With a fairly typical scaffold generated view with links:

<% @chapter.cards.each do |card| %>
    <%= link_to 'Edit', edit_card_path(card) %>
<% end %>

Now, if I try to pull it up in the browser, I get errors like this:

No route matches {:action=>"edit", :controller=>"cards", :id=>#<Card id: nil, side1: nil, side2: nil, chapter_id: 6, created_at: nil, updated_at: nil>}

It's showing the ID being nil which isn't true because I can display the other values on this record.

Why is this happening? How can I fix it?


Looks like something changed with the way nested models work in Rails 3.1. From what I can tell, calling @chapter.cards.new adds a blank card model to the top of the @chapter.cards stack, which it didn't used to to. So instead of calling @chapter.cards.new and iterating over the @chapter.cards array in the same action, I will have to keep these separate:

def show
  @book = Book.find(params[:book_id])
  @chapter = Chapter.find(params[:id])
  @card = Card.new
  @card.chapter_id = @chapter.id
  respond_with(@chapter)
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜