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

…衆ロ難τιáo~ 提交于 2019-12-05 12:14:39

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!