Rails 3.0.10 - 嵌套路由无法正常工作

时间:2012-01-08 22:53:19

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

页面底部控制器代码的要点

我有一个简单的导轨嵌套项目,我正在练习,并且我遇到了一个我似乎无法发现的问题。

当我访问网址时:localhost:3000/authors/1/books我会收到所有图书 - 而不是与ID = 1的作者对应的图书。

以下是我的一些代码:

我有作者模型和控制器,以及 Book 作者和控制器:

class Author < ActiveRecord::Base
  has_many :books
end


class Book < ActiveRecord::Base
  belongs_to :author
end

routes文件如下所示:

resources :authors do
    resources :books    
  end

以下是图书的迁移:

class CreateBooks < ActiveRecord::Migration
  def self.up
    create_table :books do |t|
      t.string :title
      t.integer :author_id

      t.timestamps
    end
  end

  def self.down
    drop_table :books
  end
end

它包含 author_id

的属性

我在Books _form.html.erb文件中也有此代码:

<div class="field">
    <%= f.label :author_id %><br />
    <%= f.collection_select(:author_id, Author.all, :id, :first_name) %>
  </div>

我可以从下拉框中选择作者并成功保存。数据库显示author_id确实被保存到相应的Book模型。

当我运行 rake routes 时,我将其作为其中一条路线:

author_books GET    /authors/:author_id/books(.:format)

但是,当我尝试这个网址时 - 我只会获得所有图书的列表。不是与正确作者相对应的书籍。

此外,我将控制器设置为返回JSON,当我放置localhost:3000/authors.json时,它返回正确的JSON对象,但是当我放localhost:3000/authors/1/books.json时,它返回&#39; null &#39;

以下是我当前数据库列表的屏幕截图,以显示数据肯定存在:

enter image description here

你能看到任何可能导致问题的事吗???如果您需要,我可以提供更多代码。


修改

运行rails console后我得到了正确的数据 - 所以我不确定为什么这条路线仍无法正常工作:

irb(main):002:0> Author.find(1).books
=> [#<Book id: 1, title: "Carrie", author_id: 1, created_at: "2012-01-08 21:20:57", updated_at: "201
2-01-08 21:20:57">]

以下是完整路线的要点: https://gist.github.com/1580058

以下是图书馆管理员: https://gist.github.com/1580064

以下是作者控制器: https://gist.github.com/1580134

抱歉,刚刚意识到我错过了最初的问题 - 我已经获得了图书的整个列表,而不是作者 - 更正了

1 个答案:

答案 0 :(得分:2)

您需要在控制器中向我们展示您的索引操作。我猜你有Book.all ......你需要

@author = Author.includes(:books).find(params[:author_id])

你也可能想要

@books = @author.books

同样在你的show方法中确保你这样做

@author = Author.find(params[:author_id])
@book = @author.books.find(params[:id])

而不是

@book = Book.find(params[:id])
相关问题