Changes in not model not adding methods to classes
I made changes to two classes to link them by this way
class Account < ActiveRecord::Base
belongs_to :customer,:foreign_key=>'name_id'
end
class Customer < ActiveRecord::Base
has_many :accounts
end
I have data in two tables that has the the referencing key 'name' in Customer and 'name_id' in Account matched. But still when I go to 'script/console' and type
Account.find(开发者_如何转开发0).customer
I get nil even when there is matching data! What is my mistake here? Sorry if its a dumb question by I'm new to rails
Had me thinking per your comment to Shyam. When adding your custom keys, are the fields in there own migration file, or were they included in the migration files when you first ran db:migrate? If these columns are already there, then yes, simply saving the model should do the trick.
You could do a quick: Account
and Customer
in your rails console to make sure these classes are built correctly, and it's the relationship that's giving you the issues.
On a side note, I'd move away from using "name" as your primary key as soon as possible. It's bad design and will cause you headaches down the road. This isn't just a rails thing, just think, how many John Smith's are in the phone book? You'd then have to use a combo key with address, and maybe more to get a unique row. And if you think about it, the phone book has a unique phone number as the identifier, it's just sorted by name.
If I understand correctly, I think you need to set :foreign_key
and :primary_key
on both associations.
class Account < ActiveRecord::Base
belongs_to :customer,:foreign_key=>'name_id', :primary_key=>'name'
end
class Customer < ActiveRecord::Base
has_many :accounts, :primary_key=>'name', :foreign_key=>'name_id'
end
You really should be following Rails conventions: the foreign key in your accounts
table should be customer_id
. Changing it to that will solve the problems you're having.
Primary keys start at 1, try: Account.find(1).customer
精彩评论