Ruby on Rails的 - 如何使关系工作在路由,控制器,查看?的has_many,belongs_to的 [英] ruby on rails - how to make relationship works in route, controller, view ? has_many, belongs_to
问题描述
我努力让我在轨工作的关系。
I am struggling to get my relationship in rails to work.
我有一个用户,画廊,Comment模型
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
现在我应该怎么在路由,控制器和意见做链接这一切吗?
请帮帮我 ?其相当混乱找出答案。如果可以,我不希望它被嵌套像railscast,但我想每个模型,如画廊,我可以输入用户,如评论我能找到和输入galleryid和用户ID。
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.
推荐答案
这是一个复杂的问题,你不能简单地告诉怎么做,但我会尽力帮助一点点。 Zippie的建议是一个很好的,你应该通过一个教程,了解不同类型的关系。
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
这是Rails会用它来搭配你的模型(外指数在去指定belongs_to的关系模型)。
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])
此将注释的USER_ID设置为当前用户,例如
This will set the comment's user_id to the current user, for example.
在视图中,没有太多的区别,只是让@comments变量,像这样的控制器:
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.
这篇关于Ruby on Rails的 - 如何使关系工作在路由,控制器,查看?的has_many,belongs_to的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!