开发者

How to set up my belongs_to and has_many reference

开发者 https://www.devze.com 2022-12-24 07:13 出处:网络
I have an ExpenseType object that I have created with the following migration: class CreateExpenseTypes < ActiveRecord::Migration

I have an ExpenseType object that I have created with the following migration:

class CreateExpenseTypes < ActiveRecord::Migration
  def self.up
    create_table :expense_types do |t|
      t.column :name, :string, :null => false
      t.timestamps
    end
  end

I can see the table name is the pluralised expense_types. My question is, how do I reference this type in a belongs_to relationship?

Is it:

belongs_to :expensetype

or is it

   belo开发者_如何学编程ngs_to :expense_type

I do not seem able to set it up correctly.

Also, how would I reference the object if it was contained in an expense object like this:

class Expense < ActiveRecord::Base
  belongs_to :expense_type
end

would it be:

expense.expense_type

or

expense.expensetype

Cheers


You are correct with:

# app/models/expense.rb
class Expense < ActiveRecord::Base
  belongs_to :expense_type
end

You can also setup ExpenseType as follows:

# app/models/expense_type.rb
class ExpenseType < ActiveRecord::Base
  has_many :expenses
end

Also, if expense is an instance of Expense, you can access the expense_type as:

expense.expense_type

For more information

see ActiveRecord::Associations::ClassMethods

0

精彩评论

暂无评论...
验证码 换一张
取 消