Rails:在显示页面中显示名称而不是Id

时间:2017-10-11 09:14:13

标签: ruby-on-rails ruby ruby-on-rails-4

我有两个表格accountsitems,我想show buisness_name而不是id来自view/items/show.html.erb帐户表{ {1}}页面。

目前我在模型之间没有关联,但我在account_id表中有items列。

 create_table "accounts", force: :cascade do |t|
    t.string "buisness_name"
    t.string "web_site"
    t.string "phone_number"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
 end

create_table "items", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.string "image"
    t.decimal "price"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "category_id"
    t.json "attachments"
    t.integer "account_id"
end

我通过此account_id获取了<%= @item.account_id %>,但我想改为显示buisness_name

2 个答案:

答案 0 :(得分:2)

尝试这样的事情

class Item < ActiveRecord::Base
  belongs_to :account 
end

进入视图

<% if @item.account %>
  <%= @item.account.buisness_name %>
<% end %>

应该是business_name,正如@Sergio Tulentsev告诉你的那样

我更新了我的答案,因为我从表中注意到account_id没有not null约束

答案 1 :(得分:2)

如果你有

<%= @item.account_id %>

获取帐户的可怕方式是

<%= Account.find_by(id: @item.account_id).try(:buisness_name) %>

更聪明的是

class Item

  belongs_to :account

  delegate :buisness_name, to: :account, prefix: true, allow_nil: true 

然后在视图中......

<%= @item.account_buisness_name %>