所以我有這個數據庫,用戶可以借用一本書。我們有書籍,用戶和借用人。嘗試在一個視圖中列出來自多個模型的信息
的代碼可以在這裏找到:https://gist.github.com/Veske/8490542
我想知道,我怎樣才能讓這個我顯示所有的書借視圖,然後還可以選擇thoes書借我的自我或另一個用戶?
如果我試圖在視圖的借用控制器中創建圖書實例變量,地獄會變得鬆散。所以我真的不知道現在..
編輯:視圖中的@book不再需要,因爲它沒有工作,我有一個行動控制器之前。
這是我的控制器:
class BurrowsController < ApplicationController
before_action :signed_in_user, only: [:index,:edit,:update, :destroy]
before_action :admin_user, only: :destroy
def index
@burrow = current_user.burrows.build
@burrows = Burrow.all
end
def show
@burrow = Burrow.find(params[:id])
end
def new
@burrow = current_user.burrows.build
end
def create
@burrow = current_user.burrows.build(burrow_params)
if @burrow.save
flash[:success] = "Burrowing a book was successful!"
redirect_to @burrow
else
render current_user
end
end
# Private section, makes the page unable to be seen for non logged in users
private
def burrow_params
params.require(:burrow).permit(:user_id, :book_id)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
# Redirecting not logged in user etc.
def signed_in_user
unless signed_in?
store_location
redirect_to '/sessions/new', notice: "Please sign in!"
end
end
end
這是我創建一個新的借項視圖:
<% provide(:title, "Burrow a book") %>
<b align="center">Choose the name of a book you want to burrow and enter 'Submit!'</b>
<%= form_for(@burrow) do |f| %>
<div class="forms">
<%= f.text_field :book_id, placeholder: "Type in the name of the book...", autofocus: true %>
<%= f.submit 'Submit!' %>
</div>
<% end %>
的觀點是壞目前,我與是絕對的一切嘗試所有的時間現在,我只是不明白需要做什麼。
借力指數:
<% provide(:title, 'All burrowers') %>
<h2 align="center">All borrowers</h2><
<table align="center">
<tr>
<td align="left"><b>Who borrowed</b></td>
<td align="left"><b>Borrowed what</b></td>
<% if current_user.admin? && !current_user?(@user) %>
<td align="left"><b>Admin functions</b></td>
<% end %>
</tr>
<% @burrows.each do |burrow| %>
<tr>
<td align="left"><%= link_to burrow.user.name, burrow.user %></td>
<td align="left"><%= link_to burrow.book.name, burrow.book %></td>
<% if current_user.admin? && !current_user?(@user) %>
<td>
<%= link_to "Delete this user", burrow, method: :delete, data: { confirm: "You sure?" } %>
</td>
<% end %>
</tr>
<% end %>
</table>
請不要鏈接到你的代碼。把它放在你的問題。 – Mischa
編輯原帖。觀點部分對我來說一直在變化,所以它只是對結構進行一個預測。但是,是的,它應該有一些方法來選擇所有的書籍,並選擇一個借書。 – Kaspar
「私人部分,使頁面無法被未登錄用戶看到」,這完全不是私人的! – Mischa