[Rails] Re: Single Table Mapping

Tom Mornini
Mon, 10 Apr 2006 16:01:43 -0000

On Apr 10, 2006, at 8:19 AM, Tom Mornini wrote:

> On Apr 10, 2006, at 7:14 AM, The Barge wrote:
>
>> OK, well I got it to work by changing the table format and
>> removing the
>> role_id from the USERS table and adding a user_id to the ROLES table
>> then adding a has_one :role to the user model.
>>
>> But is there not a way for it to map by using the role_id in the
>> USERS
>> table?  Since its a one-to-one relationship I don''t see the
point of
>> having a row in the ROLES table for each user when all I really
>> need is
>> a single column in the USERS table.
>>
>> The Barge wrote:
>>> This is pretty simple, but I must be missing the obvious.
I''ve
>>> got a
>>> table that''s similar to this:
>>>
>>> USERS:
>>> - id int
>>> - username varchar(64)
>>> - password varchar(64)
>>> - role_id int
>>>
>>> ROLES:
>>> - id int
>>> - description varchar(16)
>>>
>>> I''ve had no troubles doing has_many relationships at all.
But I
>>> want to
>>> map the user.role directly to the role model automatically (which
>>> sounds
>>> like it should be really simple).  Right now if I look at the
user''s
>>> attributes the correct role_id is shown, but I get a no method
>>> error if
>>> I try and access user.role.
>>>
>>> Do I need to do anything to tell rails to create a role model for
>>> the
>>> user?
>
> You need to use has_one instead of has_many

Oops, my advice was wrong.

You want belongs_to.

--
-- Tom Mornini