我有一个跟踪电影租赁的Rails应用程序。我在租借表和我的客户表之间建立了关系。每个租金都与一个客户相关联。Rails应用程序 - 显示客户名称
在新的租赁视图中,我有一个表格显示所有租金及其基本信息。我想显示的客户名称是每个租用的行。现在我有r.customer_id,它为出租提供了customer_id。但我想要那个人的名字。这里是我的 “新” 出租观点:
<h4 class='white'>Rental Records</h4>
<% if @movie.rentals.exists? %>
<div class="bg_white">
<table class="table table-hover table-striped">
<tr>
<th>Borrowed</th>
<th>Returned</th>
<th>Customer</th>
<th></th>
<th></th>
</tr>
<% for r in @movie.rentals.order(borrowed_on: :desc) %>
<% if !r.borrowed_on.nil? %>
<% if r.returned_on.nil? %>
<tr class="red">
<td>
<%= r.borrowed_on %>
</td>
<td>
<%= r.returned_on %>
</td>
<td>
<%= r.customer_id %>
</td>
<td>
<%= link_to "Update", edit_movie_rental_path(@movie, r) %>
</td>
<td>
<%= link_to "Delete", movie_rental_path(@movie, r), method: :delete %>
</td>
</tr>
<% else %>
<tr>
<td>
<%= r.borrowed_on %>
</td>
<td>
<%= r.returned_on %>
</td>
<td>
<%= r.customer_id %>
</td>
<td>
<%= link_to "Update", edit_movie_rental_path(@movie, r) %>
</td>
<td>
<%= link_to "Delete", movie_rental_path(@movie, r), method: :delete %>
</td>
</tr>
<% end %>
<% end %>
<% end %>
</table>
</div>
<% else %>
<p class="white"><i>No rentals to show</i><br /><br /></p>
<% end %>
出租型号:
class Rental < ApplicationRecord
has_one :movie
has_one :customer
end
客户模式:
class Customer < ApplicationRecord
has_many :rentals
def full_name
"#{self.fname} #{self.lname}"
end
end
路线:
Rails.application.routes.draw do
resources :customers
resources :movies do
resources :rentals
end
root 'movies#new'
end
客户控制器:
class CustomersController < ApplicationController
def new
@customer = Customer.new
@customers = Customer.all.order(lname: :asc).paginate(:page => params[:page], :per_page => 15)
end
def create
@customer = Customer.new(customer_params)
if @customer.save
redirect_to new_customer_path
end
end
def edit
@customer = Customer.find(params[:id])
end
def update
@customer = Customer.find(params[:id])
@customer.update(customer_params)
if @customer.save
redirect_to new_customer_path
end
end
def destroy
@customer = Customer.find(params[:id])
@customer.destroy
if @customer.destroy
redirect_to new_customer_path
end
end
private
def customer_params
params.require(:customer).permit(:fname, :lname, :telephone, :email)
end
end