Yagiz
Yagiz

Reputation: 1033

Rails belongs_to returns nil class

I am trying to link two tables to each other

class Musers < ActiveRecord::Base
    # Email 
    # sid (student_id:integer)
    # isyk: boolean

    belongs_to :user, :foreign_key => "smail"
end

class Users < ActiveRecord::Base

    belongs_to :muser, :foreign_key => "email"

end

But,

@user = Users.first
@user.muser returns nil

Upvotes: 0

Views: 930

Answers (2)

Robert Kajic
Robert Kajic

Reputation: 9077

By saying :foreign_key => "smail" you are telling rails that the Muser column smail points to the User model's foreign key. This is most likely not the case.

Assuming that the primary key of the User models is called id, you should a user_id field to Muser, and change belongs_to :user, :foreign_key => "smail" into:

belongs_to :user

On the User model you can define the reverse relation using:

has_one :muser

Also, to follow rails model naming conventions, you should rename Users to User and Musers to Muser.

You should read more about belongs_to and has_one.

If, on the other hand, the User model in fact uses email for it's primary key, I would strongly advise you to change that and add an auto-incrementing primary key instead. As a rule of thumb, the primary key should be chosen such that it never changes. If it does change, all foreign keys pointing to that primary key will have to change as well. You should only use a non auto-incrementing primary key if you have a specific reason for doing so.

More information on choosing a primary key: How to choose my primary key?

Upvotes: 1

OneChillDude
OneChillDude

Reputation: 8006

Well you can't just tell rails the type of association, you actually have to set the association to an instance of that class. For example, making a new muser will not automatically assign a user as the belongs_to. You could do something like

u = User.new
u.muser = Muser.first
u.save

However, I'm not sure what you are trying to accomplish with a belongs_to - belongs_to relationship, but you should know that you have to do more than just tell rails it exists.

Upvotes: 1

Related Questions