刚刚解决了在我的 SHOW 视图中链接到关联模型的问题,但相同的答案不适用于我的 INDEX 视图。
我正在尝试做的工作,但不能是制造商位,它是属于 Miniatures 的模型。表格很好,但我无法让制造商正确显示和链接。抱歉,这不清楚。
我的缩影index.html.erb
<% provide(:title, 'All miniatures') %>
<h1>All miniatures</h1>
<%= will_paginate %>
<table border="0" cellpadding="10">
<th align="left">Name</th>
<th align="left">Material</th>
<th align="left">Manufacturer</th>
<th align="left">Scale</th>
<th align="left">Product Code</th>
<th align="left">Sculpted by</th>
<th align="left">Release date</th>
<% if current_user.try(:admin?) %><th align="left">Admin</th><% end %>
<%= render @miniatures %>
</table>
<%= will_paginate %>
<h1> Import Miniatures</h1>
<%= form_tag import_miniatures_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
这使得这个部分显示缩影:
<tr>
<td><%= link_to miniature.name, miniature %></td>
<td><%= miniature.material %></td>
<td><%= link_to manufacturer.name, manufacturer_path(manufacturer)</td>
<td>scale</td>
<td><%= miniature.pcode %></td>
<td>sculptor</td>
<td><%= miniature.release_date %></td>
<td><% if current_user.try(:admin?) %>
<%= link_to "delete", miniature, method: :delete,
data: { confirm: "You sure?" } %>
<% end %></td></tr>
我可以看到它不能与我的视图一样工作,因为我有一个|manufacturer|
我在这里没有的命名实例。我想我需要在控制器中定义它?在索引下?
这是我的(略微裁剪的)MiniaturesController
class MiniaturesController < ApplicationController
before_action :signed_in_user, only: [:new, :create, :edit, :update]
before_action :admin_user, only: :destroy
def import
Miniature.import(params[:file])
redirect_to root_url, notice: "Miniatures imported."
end
def show
@miniature = Miniature.find(params[:id])
end
def new
@miniature = Miniature.new
@miniature.productions.build
@miniature.sizes.build
@miniature.sculptings.build
end
def create
@miniature = Miniature.new(miniature_params)
@production = @miniature.productions.build
@size = @miniature.sizes.build
@sculpting = @miniature.sculptings.build
if @miniature.save
redirect_to @miniature
else
render 'new'
end
end
def edit
@miniature = Miniature.find(params[:id])
end
def update
@miniature = Miniature.find(params[:id])
if @miniature.update_attributes(miniature_params)
flash[:success] = "Miniature updated"
redirect_to @miniature and return
end
end
end
end
render 'edit'
end
def index
@miniatures = Miniature.paginate(page: params[:page])
end
def destroy
Miniature.find(params[:id]).destroy
flash[:success] = "Miniature destroyed."
redirect_to miniatures_url
end
private
def miniature_params
params.require(:miniature).permit(:name, :release_date, :material, :pcode, :notes, productions_attributes: [:id, :manufacturer_id, :miniature_id], sizes_attributes: [:id, :scale_id, :miniature_id], sculptings_attributes: [:id, :sculptor_id, :miniature_id])
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end
end
end