railsway
railsway

Reputation: 1

Id's in rails application

In my application I have a user model and a address model. How do I have the address form to include the id of the user id. (i.e my address model has a id and a id_user)?

Upvotes: 0

Views: 66

Answers (2)

Pierre-Luc Simard
Pierre-Luc Simard

Reputation: 2721

You probably want to look into record associations. I strongly recommend the guide on that very subject on the Rails website.

Since you took the time of creating two separate models (one for users and one for addresses) I figure it's because you can have one or more adresse per user. So I would recommend using a has_many association

In your migration file for your address model you should have a column name user_id of type integer. By convention, rails will use columns named model_id for an association with a model. So in your case, the model user can be linked with an address through the column user_id.

Having the column is not enough however. You also need to tell Rails about the association in the model. So add the following to the top of your user model (app/model/user.rb I would presume)

has_many :addresses

Then, tell your address model it belongs to a user. Doing so is again very straight forward. Add the following at the top of your address model (app/model/address.rb)

belongs_to :user

From there, you can do all sort of wonderful things. To create your forms, you may want to look at Nested model forms. There's two Railscast on it Part 1 and Part 2

As your experience with Rails seems limited at the time. I'd recommend also looking into the getting started guide, looking at the series of tutorial from Envy Labs (comically named Rails for Zombies) and when you get rolling browse through the Railscasts by Ryans Bates

Upvotes: 0

Ryan Bigg
Ryan Bigg

Reputation: 107718

Your address model should contain a user_id field, not a id_user field. It seems like you're just getting started with Rails, so I would recommend reading the official Getting Started and Association basics guides to learn the basics.

Upvotes: 1

Related Questions