我正在尝试显示用户图书的列表,但由于某种原因,保存的图书不会显示在视图上。应用程序应该允许已登录的用户保存图书,然后显示保存的图书列表那个特定的用户。这是我的代码..
<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>
BOOK CONTROLLER
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 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 Book < ActiveRecord::Base
has_many :book_ownerships
has_many :users,:through => :book_ownerships
end
用户模型
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 BookOwnership < ActiveRecord::Base
belongs_to :user
belongs_to :book
end
预订视图
<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%>
答案 0 :(得分:1)
我假设您示例中的第一个视图实际上是Books#index
而不是Home#index
,如果这是真的,那么您需要将变量@books
设置为控制器中的某个内容。 / p>
使BooksController中的索引操作看起来应该足够了:
def index
@books = current_user.books
end
至少如果您使用的是Rails 3.如果您使用的是早期版本,那么您应该将调用添加到all方法中,如下所示:
@books = current_user.books.all