开发者

Linking models in Ruby on Rails

I"m building a Rails app, and there are two models that I want to connect.

开发者_如何学JAVA

There's a model called "users" that handles user authentication, e.g. username and password data. Then there's a model called "profiles" that has a person's location, description, etc, etc.

I want to link the models so that there's one profile per user. I really don't know how to do this. Anyone mind sharing some insight on how this can be done?


take a look at rails associations basics

your asociation will look like

class User < AR:Base
  has_one :profile
end

class Profile < AR:Base
  belongs_to :user
end

oh, the table profiles must have a user_id column with the foreign key to the user.


You want a has_one and belongs_to association on your User model and your Profile model. Your profile model will likely have a user_id column and will be the "belongs_to" relationship, while the User will have no column for the profile and will be the "has_one" relationship.

Then in your code you can do this:

profile = some_user.profile

or

user = some_profile.user


This sounds like a one-to-one association. Here's how you would set it up:

class User < ActiveRecord::Base
  has_one :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end

Rails makes this kind of relationship super simple. :)

Make sure the Profiles table has a user_id column so this association will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜