【问题标题】:Show contact name from the contact id column stored in my invoice table in ruby on rails在 ruby​​ on rails 中显示存储在我的发票表中的联系人 ID 列中的联系人姓名
【发布时间】:2014-10-21 10:19:12
【问题描述】:

我显然是使用 Ruby on Rails 4 开发的新手。我有一个 Company 模型、一个 Contact 模型和一个 Invoice 模型。联系人嵌套在公司中,发票嵌套在公司中。我的 Invoice 表有一个 contact_id 列,该列基于从 @company.contacts 填充的下拉菜单存储在我的 invoice 表中。我不想显示@invoice.contact_id(即10),而是从联系人表中显示contact_id 10 的名字。 我很确定我需要在发票控制器中定义@contacts,但似乎无法找到正确的语法来表示获取contact_id 的名称,其中contact.id = @invoice.contact_id

Routes.rb

resources :companies do
  resources :contacts 
  resources :invoices 
end

Company.rb

class Company < ActiveRecord::Base
  has_many :invoices
  has_many :contacts
end

Contact.rb

class Contact < ActiveRecord::Base
  belongs_to :company
end

Invoice.rb

class Invoice < ActiveRecord::Base 
  belongs_to :company 
  has_many :contacts, through: :company 
end

Schema.rb

create_table "companies", force: true do |t|
t.string   "name"
t.string   "street"
t.string   "city"
t.string   "province"
t.string   "postal_code"
t.string   "tel"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "contacts", force: true do |t|
t.integer  "company_id"
t.string   "first_name"
t.string   "last_name"
t.string   "title"
t.string   "tel"
t.string   "email"
t.datetime "created_at"
t.datetime "updated_at"
end

add_index "contacts", ["company_id"], name: "index_contacts_on_company_id", using: :btree

create_table "invoices", force: true do |t|
t.integer  "company_id"
t.integer  "contact_id"
t.integer  "item_id"
t.decimal  "total",      precision: 7, scale: 2
t.datetime "created_at"
t.datetime "updated_at"
end
  add_index "invoices", ["company_id"], name: "index_invoices_on_company_id", using: :btree
add_index "invoices", ["contact_id"], name: "index_invoices_on_contact_id", using: :btre
add_index "invoices", ["item_id"], name: "index_invoices_on_item_id", using: :btree

【问题讨论】:

  • 您能发布您的架构吗?我认为你已经让你的协会磨损了。如果invoicecontact_idinvoice 应该是belong_to contact
  • 我已将我的 shcema 添加到我的原始帖子中

标签: ruby-on-rails postgresql


【解决方案1】:

使用 Rails 很容易实现:

# controller
def index
  @invoices = Invoice.all.includes(:contacts) # .inclutes(:contacts) is Eager Loading (n+1 Queries)
end

# view
@invoices.each do |invoice|
  invoice.contacts.each do |contact|
    contact.name
  end
end

【讨论】:

  • 感谢@MrYoshiji 的工作。它列出了所有联系人姓名。但在这种情况下,我只想在发票表中显示contact_id 的名称,所以如果我的发票表中的contact_id 为10,我想从联系人表中显示该联系人的名称10
猜你喜欢
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 2018-10-18
  • 2014-03-02
  • 2021-02-28
  • 2012-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多