2017-10-11 23 views
0

显示名称,而不是标识我有两个表,accountsitems,我想从账目表showbuisness_name代替idview/items/show.html.erb页面上。的Rails:在节目页

目前我没有模型之间的关联,但我有表中的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 

我得到通过这个account_id<%= @item.account_id %>,但我想,以显示buisness_name代替。

+0

JFYI,这是“业务”,而不是“ buisness“ –

+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约束

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 %> 
+3

可能要在该委托上使用'prefix:true'。物品通常不会有商业名称。 :) –

+0

@SergioTulentsev好点。 – SteveTurczyn