Rails 4关联显示名称而不是ID

时间:2014-05-20 11:55:38

标签: ruby-on-rails ruby activerecord

如何显示姓名而不是ID?它必须如此简单,但它无法正常工作。

模特:

class CyclingTeam < ActiveRecord::Base
  has_many :riders
end

class Rider < ActiveRecord::Base
  belongs_to :cycling_team
  belongs_to :country

  has_many :tour_teams
end

class Country < ActiveRecord::Base
  has_many :riders
end

然后我有一个视图:

<tr>  
<td><%= rider.name %></td>  
<td><%= rider.birthday %></td>  
<td><%= rider.country.name %></td>  
<% if current_user.try(:admin?) %>  
<td><%= link_to 'Edit', edit_rider_path(rider) %></td>  
<% end %>  
</tr>  

表单正在运行,但简单的观点是不是。任何人都可以帮忙吗?感谢。

额外:

class RidersController < ApplicationController
before_action :set_rider, only: [:show, :edit, :update, :destroy]

  # GET /riders
  # GET /riders.json

def index
    @riders = Rider.all
    @rider = Country.all
   end

  # GET /riders/1
  # GET /riders/1.json
  def show
    @riders = Rider.all
    @rider = Country.all  
  end

 # GET /riders/new
  def new
   @rider = Rider.new
 end

  private
   # Use callbacks to share common setup or constraints between actions.
    def set_rider
      @rider = Rider.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def rider_params
       params.require(:rider).permit(:name, :birthday, :tdf, :allround, :climber,      :sprinter, :classic, :yellow, :green, :white, :polka, :cycling_team__attributes => [:id, :name], :country_attributes => [:id, :name])
    end
end
希望它有所帮助。

1 个答案:

答案 0 :(得分:0)

这不对......

  def show
    @riders = Rider.all
    @rider = Country.all  
  end

您正在将实例变量@rider设置为等于覆盖您的set_rider方法正在执行的所有国家/地区的数组。您还要为所有车友设置@riders,而您在展会页面上并不需要。

作为替代..在你的Rider模型上创建一个方法......

country_name
  self.country.name if self.country
end
控制器中的

在节目中什么都不做......

def show
end

...您可以在视图中输出@ rider.country_name。

<%= @rider.country_name %>