Ruby on rails 用户和书籍之间的多对多关系,书籍不会出现在视图中

Ruby on rails 用户和书籍之间的多对多关系,书籍不会出现在视图中,ruby-on-rails,has-many-through,Ruby On Rails,Has Many Through,我试图显示用户的书籍列表,但由于某些原因,保存的书籍不会显示在视图中。应用程序应该允许登录用户保存书籍,然后显示该特定用户保存的书籍列表。这是我的密码 <h1>Home#index</h1> <%=link_to 'add a book',new_book_path%> <ul> <% @books.each do |b|%> <li><%= b.title %></li> <li>

我试图显示用户的书籍列表,但由于某些原因,保存的书籍不会显示在视图中。应用程序应该允许登录用户保存书籍,然后显示该特定用户保存的书籍列表。这是我的密码

<h1>Home#index</h1>
<%=link_to 'add a book',new_book_path%>
<ul>
 <% @books.each do |b|%>
 <li><%= b.title %></li>
 <li><%= b.author %></li>
 <%end%>
 </ul>
Home#索引
图书管理员

class BooksController < ApplicationController
def index

 end

def create

@book=current_user.books.build(params[:book])
if @book.save
redirect_to '/home/index'
else
  render :action =>'new'
end
end


def new
@book=Book.new
end
end   
class BooksController'new'
结束
结束
def新
@书
结束
结束
家庭控制器

class HomeController < ApplicationController
#kip_before_filter    :authenticate_user! 
 #efore_filter :homenticate_user! 

 def index
  @books=current_user.books

 end

 def show
 end

 def welcome

 end
 end
class HomeController
图书模型

class Book < ActiveRecord::Base
has_many :book_ownerships
has_many :users,:through => :book_ownerships
end
classbook:图书所有权
结束
用户模型

 class User < ActiveRecord::Base
 has_many :book_ownerships
 has_many :books,:through => :book_ownerships
 has_many :skills
 # Include default devise modules. Others available are:
 # :token_authenticatable, :lockable, :timeoutable and :activatable
 devise :database_authenticatable, :registerable, 

     :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation,:firstname
  end
class用户:书籍所有权
有很多技能
#包括默认设计模块。其他可供选择的项目包括:
#:token_authenticable、:lockable、:timeoutable和:activatable
设计:数据库可验证,可注册,
:可恢复,:可记忆,:可跟踪,:可验证
#设置模型的可访问(或受保护)属性
属性可访问:电子邮件、:密码、:密码确认、:名字
结束
图书所有权模式

 class BookOwnership < ActiveRecord::Base
 belongs_to :user
 belongs_to :book
 end
class BookOwnership
书景

<h1>Book#new</h1>
<p>Find me in app/views/book/index.html.erb</p>
 <%= form_for(@book) do |f|%>
 <%=f.text_field :title%>
 <%=f.text_field :author%>
 <%=f.submit%>
 <%end%>
Book#new
在app/views/book/index.html.erb中查找我


我假设您示例中的第一个视图实际上是
Books#index
而不是
Home#index
,如果这是真的,那么您需要将变量
@Books
设置为控制器中的某个值

它应该足以使BookController中的索引操作如下所示:

def index
  @books = current_user.books
end
@books = current_user.books.all
至少如果您使用的是Rails 3。如果您使用的是早期版本,则应向all方法添加调用,如下所示:

def index
  @books = current_user.books
end
@books = current_user.books.all

@dannmanne不,就像Homeindex一样,我想展示Homeindex视图上的书籍。谢谢你,好的,如果是这样,你能用你家的代码补充一下吗#索引控制器动作?看看它是什么样子会很有帮助。@katie您需要在您的家庭控制器的索引操作中设置实例变量,正如Danne上面所示。我还猜测您是通过Desive的before_过滤器授权控制器-如果不是,请不要假设当前用户存在。@dannmanne我在上面添加了home controller…@mike需要在home视图中显示这些书籍,这就是为什么当我查看代码时,您的代码看起来应该可以工作的原因。您确定当前用户在数据库中确实有任何书籍吗?如果您是,我建议您使用一些调试日志记录,例如将其放入主控制器中的索引操作中:
logger.info(当前用户.inspect)
logger.info(@books.inspect)
,然后开始查看日志文件