Ruby on rails Rails:在显示页面中显示名称而不是Id
我有两个表,Ruby on rails Rails:在显示页面中显示名称而不是Id,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我有两个表,accounts和items,我想显示business\u name,而不是view/items/show.html.erb页面上accounts表中的id 目前,我在模型之间没有关联,但我在项目表中有账户id列 create_table "accounts", force: :cascade do |t| t.string "buisness_name" t.string "web_site" t.string "phone_number" t.d
accounts
和items
,我想显示business\u name
,而不是view/items/show.html.erb
页面上accounts表中的id
目前,我在模型之间没有关联,但我在项目
表中有账户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
我通过以下方式获得帐户id
:
,但我想显示业务名称
。试试这样的方法
class Item < ActiveRecord::Base
belongs_to :account
end
class项
进入视野
<% if @item.account %>
<%= @item.account.buisness_name %>
<% end %>
正如@Sergio Tulentsev已经告诉您的那样,应该是业务名称
我更新了我的答案,因为我从表中注意到帐户\u id
没有notnull
约束
class Item < ActiveRecord::Base
belongs_to :account
end
class项
进入视野
<% if @item.account %>
<%= @item.account.buisness_name %>
<% end %>
正如@Sergio Tulentsev已经告诉您的那样,应该是业务名称
我更新了我的答案,因为我从表中注意到帐户\u id
没有notnull
约束(如果有)
<%= @item.account_id %>
然后在视图中
<%= @item.account_buisness_name %>
如果您有
<%= @item.account_id %>
然后在视图中
<%= @item.account_buisness_name %>
JFYI,这是“业务”,而不是“业务”当前我在模型之间没有关联”-这是您需要解决的问题。JFYI,这是“业务”,而不是“业务”当前我在模型之间没有关联”-这是您需要解决的问题。可能需要在该代理上使用前缀:true
。项目通常没有业务名称。:)你也可以做@item.account.try(:bussiness\u name)
,这很干净。委托解决方案工作得很好,但是如果您发现自己需要这样的多个场景以及视图中的许多条件,您可能需要检查什么是装饰器。draper gem()是一个良好的开端。可能需要在该代理上使用前缀:true
。项目通常没有业务名称。:)你也可以做@item.account.try(:bussiness\u name)
,这很干净。委托解决方案工作得很好,但是如果您发现自己需要这样的多个场景以及视图中的许多条件,您可能需要检查什么是装饰器。德雷珀宝石()是一个良好的开端。