0
我想顯示用戶書籍的列表,但由於某種原因,保存的書籍不會出現在視圖中。應用程序應該允許登錄用戶保存書籍,然後顯示該特定用戶保存的書籍列表。這裏是我的代碼..用戶和書籍之間的多對多關係,書籍不會出現在視圖中
<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控制器
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
Book模型
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%>
@dannmanne不,它是homeindex喜歡它,我想說明的homeindex書view..thank你 – katie
歐凱,在這種情況下,你能不能從您的主頁的代碼補#index控制器操作?將有助於看到如何看起來像。 – DanneManne
@katie你需要在你的home_controller的索引操作中設置實例變量,就像Danne上面顯示的一樣。我也猜測你是通過Devise的before_filter來授權控制器 - 如果沒有,不要假設current_user存在。 –