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

1

5

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.

Undercarriage answered 10/4, 2013 at 22:59 Comment(1)
Try passing this tutorial: ruby.railstutorial.org/ruby-on-rails-tutorial-bookPenetrating
R
8

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.

Roadster answered 10/4, 2013 at 23:38 Comment(1)
thanks awhole lot, this is similar to what i have followed here: railscasts.com/episodes/238-mongoid?view=asciicast , now you have atleast clarified on the routes, i need to figure out how to do the controllers and views. i'll have to study a bit more.Undercarriage

© 2022 - 2024 — McMap. All rights reserved.