ruby-on-rails – Rails显示belongs_to中的类别名称
发布时间:2020-12-17 02:30:38 所属栏目:百科 来源:网络整理
导读:我想显示一个类别名称,而不是来自属于关系的数字(cat_id),我有汽车和制造,基本上这里是代码 – show.html.erb p id="notice"%= notice %/pp bMake:/b %= @car.make_id % /ph2 em%= @car.model % %= @car.body_typw % %= @car.engine_size % %= @car.trim %/e
我想显示一个类别名称,而不是来自属于关系的数字(cat_id),我有汽车和制造,基本上这里是代码 –
show.html.erb <p id="notice"><%= notice %></p> <p> <b>Make:</b> <%= @car.make_id %> </p> <h2> <em><%= @car.model %> <%= @car.body_typw %> <%= @car.engine_size %> <%= @car.trim %></em> </h2> <p> <%= image_tag @car.image(:large) %> </p> <% @carimages.each do |carimage| %> <%= image_tag carimage.image(:thumb),:class => "imgsmall" %> <% end %> <p> <b>Transmission:</b> <%= @car.transmission %> </p> <p> <b>Fuel type:</b> <%= @car.fuel_type %> </p> <p> <b>Millage:</b> <%= @car.millage %> </p> <p> <b>Price:</b> <%= number_to_currency(@car.price) %> </p> <p> <%= raw @car.content %> </p> 所以基本上我想在这里取名: – <p> <b>Make:</b> <%= @car.make_id %> </p> cars_controller.rb class CarsController < ApplicationController # GET /cars # GET /cars.json def index @cars = Car.all respond_to do |format| format.html # index.html.erb format.json { render json: @cars } end end # GET /cars/1 # GET /cars/1.json def show @car = Car.find(params[:id]) @pages = Page.all @carimages = Carimage.all @carimages = Carimage.find(:all,:limit => 10,:order => "id DESC") respond_to do |format| format.html # show.html.erb format.json { render json: @car } end end # GET /cars/new # GET /cars/new.json def new @car = Car.new respond_to do |format| format.html # new.html.erb format.json { render json: @car } end end # GET /cars/1/edit def edit @car = Car.find(params[:id]) end # POST /cars # POST /cars.json def create @car = Car.new(params[:car]) respond_to do |format| if @car.save format.html { redirect_to @car,notice: 'Car was successfully created.' } format.json { render json: @car,status: :created,location: @car } else format.html { render action: "new" } format.json { render json: @car.errors,status: :unprocessable_entity } end end end # PUT /cars/1 # PUT /cars/1.json def update @car = Car.find(params[:id]) respond_to do |format| if @car.update_attributes(params[:car]) format.html { redirect_to @car,notice: 'Car was successfully updated.' } format.json { head :ok } else format.html { render action: "edit" } format.json { render json: @car.errors,status: :unprocessable_entity } end end end # DELETE /cars/1 # DELETE /cars/1.json def destroy @car = Car.find(params[:id]) @car.destroy respond_to do |format| format.html { redirect_to cars_url } format.json { head :ok } end end end 它通过make table-id和car table – make_id相关联 谢谢 罗比 解决方法
当然 – 属于关系会给你一个对象(在你的情况下是一个Make),你可以调用方法 – 包括获取字段名称!
所以,如果你设置你的模型: class Car < ActiveRecord::Base belongs_to :make end class Make < ActiveRecord::Base end 并且Make有一个名为name的字段,您可以在您的视图中: <p> <b>Make:</b> <%= @car.make.name %> </p> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |