belongs_to :keeper, :class_name => "Staff"
belongs_to "staff", :foreign_key => "keeper_id"
In my basic tests, these seem to be doing the exact same thing.
Are they indeed the same?
Is one better than the other?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The two statements define the same association. The difference is how the defined associations are referenced by the class defining those associations.
Calling belongs_to defines a whole whack of new instance methods for the calling class to handle the given relation. These new methods are named based on the first argument of belongs_to. As with most of the rest of Rails, ActiveRecord will use sensible defaults derived from the first argument to generate the methods that manage the association. Providing additional arguments to belongs_to just override those defaults.
In reality, they are identical in all but name. It all comes down to your personal preference. Would you rather refer to the association with
@model.keeperor@model.staff?Have a read through the belongs_to section of the Associations reference to get a better idea of the methods provided when a model belongs to another and how the options to belongs_to are used.