链接到INDEX视图中的关联模型

刚刚在我的SHOW视图中解决了链接到相关模型的问题,但同样的答案对我的INDEX视图不起作用。

我正在尝试做什么,而不能是制造商位,这是属于Miniature的模型。 表格很好,但我无法让制造商正确显示和链接。 对不起,这不清楚。

我的微缩模型index.html.erb

 

All miniatures

Name Material Manufacturer Scale Product Code Sculpted by Release date Admin

Import Miniatures

这使得部分显示微缩模型:

    <%= link_to manufacturer.name, manufacturer_path(manufacturer) scale  sculptor     

我可以看到它不能像我的视图一样工作,因为我有一个命名实例|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 

你不应该改变你的控制器。 微型和制造商之间的关系应该在模型层面定义,例如:

 class Miniature < ActiveRecord::Base belongs_to :manufacturer end class Manufacturer < ActiveRecord::Base has_many :miniatures end 

您的实际关系代码可能有所不同,但上面说明了这些原则。

在您的微型部分( miniatures/_miniature.html.erb )中,微型制造商可用作属性:

 <%= link_to miniature.manufacturer.name, miniature.manufacturer %> 

(注意:请注意,您可以包含对象实例,并且Rails的路由助手将自动将其转换为适当的路径,假设您已指定resources :manufacturers routes.rb文件中的resources :manufacturers )。

我觉得你在ActiveRecord协会的工作方式上有点挣扎,最终会让自己感到困惑。