ruby on rails - how to make relationship works in route, controller, view ? has_many, belongs_to

Axil picture Axil · Apr 11, 2013 · Viewed 10.5k times · Source

I am struggling to get my relationship in rails to work.

I have a User,Gallery,Comment model

class Gallery  
  has_many :comments
  belongs_to :user
end

class User  
  has_many :comments
  has_many :galleries
end

class Comment
  belongs_to :gallery
  belongs_to :user
end

now what should i do in the routes, controller and views to link this all up ? please help me ? its quite confusing finding out the answers. If can, I dont want it to be nested like in the railscast, but i want for each model, eg gallery i can input user, eg comment i can find and input the galleryid and userid.

Im totally lost in oblivion now, not knowing what to do. Please give some assistance. thanks.

Answer

Roma149 picture Roma149 · Apr 11, 2013

It's a complex subject that you can't be simply told how to do, but I'll try to help a little. Zippie's suggestion is a good one, you should go through a tutorial to learn about the different kinds of relationships.

In your database, you will need:

create_table :gallery do |t|
  t.user_id
end

create_table :comments do |t|
  t.gallery_id
  t.user_id
end

These are the foreign indices that Rails will use to match your models (the foreign index goes in the model that specifies the belongs_to relationship).

As for your routes, there is no single solution, but you might want to nest them so you can do things like /users/comments or /galleries/comments:

resource :users do
   resource :comments
end

resource :galleries do
   resource :comments
end

You could also simply have them separately:

resources :users, :galleries, :comments

In your controller, when creating a new object, you should do so from the object it belongs to:

@comment = current_user.comments.build(params[:comment])

This will set the comment's user_id to the current user, for example.

In the view, there's not much difference, just get the @comments variable in the controller like so:

@comments = @gallery.comments

and use it in your view.

It might be less intuitive when you want to define a form helper to create a new comment, for example:

<%= form_for([@gallery, @comment]) do |f| %>
  ...
<% end %>

I hope that helps you get started.