问题
I have a model with a belongs_to association:
class Car < ActiveRecord::Base
belongs_to :vendor
end
So I can call car.vendor. But I also want to call car.company! So, I have the following:
class Car < ActiveRecord::Base
belongs_to :vendor
def company
vendor
end
end
but that doesn't solve the assignment situation car.company = 'ford', so I need to create another method for that. Is there a simple alias mechanism I can use for associations? Can I just use alias_method :company, :vendor and alias_method :company=, :vendor=?
回答1:
No it doesn't look for company_id for instance change your code as follows
In Rails3
class Car < ActiveRecord::Base
belongs_to :vendor
belongs_to :company, :class_name => :Vendor,:foreign_key => "vendor_id"
end
In Rails4
We can use alias attribute.
alias_attribute :company, :vendor
回答2:
In Rails 4, you should simply be able to add alias_attribute :company, :vendor to your model.
回答3:
Short Version:
Generate model with migration
$ rails generate model Car vendor:references name:string ...Add following line in
Carmodel i.ecar.rbfileclass Car < ActiveRecord::Base belongs_to :company, :class_name => 'Vendor', :foreign_key => 'vendor_id' endNow you have
@car.companyinstance method.
For a Detailed explanation read ahead [Optional if you understood the above !!]
Detailed Version:
The model Car will have an association with the model Vendor (which is obvious). So there should be a vendor_id in the table cars.
In order to make sure that the field
vendor_idis present in thecarstable run the following on the command line. This will generate the right migration. Thevendor:referencesis important. You can have any number of attributes after that.$ rails generate model Car vendor:references name:stringOr else in the existing migration for
create_table :carsjust add the linet.references :vendorclass CreateCars < ActiveRecord::Migration def change create_table :cars do |t| t.string :name ... t.references :vendor t.timestamps end end endThe final thing that you need to do is edit the model
Car. So add this code to yourcar.rbfileclass Car < ActiveRecord::Base belongs_to :company, :class_name => 'Vendor', :foreign_key => 'vendor_id' end
After you do the third step you will get the following instance methods for the model Car provided by Rails Associations
@car.companyWhen you do
@car.companyit will return a#<Vendor ...>object. To find that#<Vendor ...>object it will go look for thevendor_idcolumn in thecarstable because you have mentioned:foreign_key => 'vendor_id'You can set the company for a car instance by writing
@car.company = @vendor || Vendor.find(params[:id]) #whichever Vendor object you want @car.saveThis will save the
idof thatVendorobject in thevendor_idfield of thecarstable.
Thank You.
回答4:
class Car < ActiveRecord::Base
belongs_to :vendor
belongs_to :company, :class_name => :Vendor
end
来源:https://stackoverflow.com/questions/21471075/possible-to-alias-a-belongs-to-association-in-rails