Rails 嵌套资源和路线以及如何在route.rb 中设置它们
我认为我可以处理嵌套路由(很棒的 url 帮助程序和访问等等)以及带有 Accepts_nested_attributes_for 的表单中的嵌套资源,但是当我看到这两者时,我在路由中使用什么:
resources :schools do
resources :documents
end
还
resources :schools :has_many => :documents
end
请你告诉我这些之间的区别.
显然 has_many 是针对一对多关系的。它是否产生路径助手并需要正确的路由,对于 do 块来说,这意味着什么关系,没有?只是路径助手(/schools/documents),如果我想要学校下的多个资源(除了书籍,比如文档),第一种方法我可以将其添加到 do-end 块中,但第二种方法呢,只需两行,每个 has_many 一个?
虽然我已经阅读了指南和 api,但我不太明白这里的区别/用法,任何人都可以提供两者之间区别的清晰解释(以“a 做 x 而 b 做 y”的形式)会很棒)将不胜感激:)
哦,当然它们与模型中的 has_many 有何关系 - 所以我猜这些关系可以在带有 has_many 的模型中,控制器(主要通过路径的使用)和视图中(通过具有嵌套属性的表单)。
I think I have a handle on nested routes (great url helpers, and access and much more) and nested resources in forms with accepts_nested_attributes_for but what do I use in routes as I see both:
resources :schools do
resources :documents
end
and also
resources :schools :has_many => :documents
end
please can you tell me the difference between these.
Obviously has_many is for a one-to-many relationship. does it produce path helpers and require correct routing and for the do block what relationship does that imply, none? just path helpers (/schools/documents) and what if I want multiple resources (other than books, say documents) under schools, the first way I can add it into the do-end block but what about the second way, just two lines, one for each has_many?
Though I've read the guides and api's I don't quite get the difference/usage here and anyone that can provide a clear explanation of the distinction between the two (in the form 'a does x whereas b does y' would be great) would be much appreciated :)
Oh and of course how they relate to having the has_many in the model - so I guess these relationships can be in the model with has_many, the controller (mostly thru usage of paths) and in the view (through forms with nested attributes).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们都做同样的事情,由你选择
我更喜欢 do 块格式,因为它更容易阅读
,顺便说一句,你可以使用 has_many 格式
:has_many =>; [:docs, :otherthings]
用于多个嵌套路由They both do the same thing, its up to you to choose which one
I prefer the do block format as its easier to read
btw with the has_many format you could do
:has_many => [:docs, :otherthings]
for multiple nested routes我认为 has_many 语法是添加到 Rails 2 中的东西,作为那些不喜欢块语法的人的简写。您可以查看有关它的博客文章 这里。我刚刚尝试了一下,似乎 Rails 3 忽略了 has_many 选项。所以我的输出是:
创建了路线:
同时
创建了路线:
我认为你问题的真正答案是那些是/应该做同样的事情,只是用不同的语法。
I think the has_many syntax was something added to Rails 2 as a shorthand for those that didn't like the block syntax. You can see a blog post about it here. I just tried it and it seems that Rails 3 ignores the has_many option. So the output for me was:
created the routes:
while
created the routes:
I think the real answer to your question is that those are/were supposed to do the same thing, just with different syntax.