【问题标题】:Rails: show name instead of Id in a show pageRails:在显示页面中显示名称而不是 Id
【发布时间】:2017-10-11 09:14:12
【问题描述】:

我有两个表,accountsitems,我想在 view/items/show.html.erb 页面上的帐户表中使用 show buisness_name 而不是 id

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

 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

我通过这个<%= @item.account_id %> 获得account_id,但我想改为显示buisness_name

【问题讨论】:

  • JFYI,这是“商业”,而不是“商业”
  • “目前我没有模型之间的关联” - 这就是你需要解决的问题。

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


【解决方案1】:

试试这样的

class Item < ActiveRecord::Base
  belongs_to :account 
end

进入视野

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

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

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

【讨论】:

    【解决方案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 %>
    

    【讨论】:

    • 可能希望在该委托上使用prefix: true。物品通常没有公司名称。 :)
    • 你也可以做@item.account.try(:bussiness_name),这很干净。委托解决方案工作正常,但如果您发现自己需要像这样的多个场景以及视图内的许多条件,您可能需要检查 decorator 是什么。 draper gem (github.com/drapergem/draper) 是一个好的开始。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多