简体   繁体   English

Rails嵌套路由的奇异​​资源

[英]Rails Nested Route For Singular Resource

I have a nested route on a singular resource 我在单一资源上有一个嵌套路由

map.resource :account, :controller => "users" do |page|
  page.resources :feeds
end

I'm trying to make a form to add a feed. 我正在尝试制作一个表单来添加Feed。 I start with this... 我从这开始......

<% form_for @feed do |f| %>
undefined method `feeds_path' for #<ActionView::Base:0x2123174>

So I try 所以我试试

<% form_for [current_user,@feed] do |f| %>
undefined method `user_feeds_path' for #<ActionView::Base:0x20b3e00>

I guess that is due to renaming it from "users" to "account"? 我想这是因为将它从“用户”重命名为“帐户”? So I tried 所以我试过了

<% form_for account_feeds_path(@feed) do |f| %>
`@/account/feeds.%23%3Cfeed:0x22ea5c0%3E' is not allowed as an instance variable name

Not sure what that error means. 不确定该错误意味着什么。 So I've resorted to using doing this which works: 所以我已经使用了这样做:

<% form_for @feed, :url=>{:action=>:create} do |f| %>

Is that really the best way? 这真的是最好的方式吗? In other words, is there no way to use named routes in this situation? 换句话说,在这种情况下是否无法使用命名路由?

I think what you want to do is 我想你想做的是

<% form_for [:account, @feed] do |f| %>

form_for will then look to use the account_feeds_path with POST when @feed is a new record and account_feed_path(@feed) with PUT when @feed is not a new record. 当@feed是新记录时,form_for将使用带有POST的account_feeds_path,当@feed不是新记录时,将使用PUT将account_feed_pa​​th(@feed)用于。

I think you're getting confused here about nested (+named) routes and singular resources. 我认为你在这里对嵌套(+命名)路由和奇异资源感到困惑。 I'm guessing that what you're trying to do is have a singular feed resource that belongs to a user (account), right? 我猜你正在尝试做的是拥有一个属于用户(帐户)的单一feed资源,对吧?

If so, your existing routes 如果是这样,您现有的路线

map.resource :account, :controller => "users" do |page|
  page.resources :feeds
end

should perhaps be 也许应该是

map.resources :accounts, :controller => "users" do |account|
  account.resource :feed
end

Note that accounts are plural resources, but the feed is singular. 请注意, accounts是多个资源,但Feed是单数。 That gives you the usual RESTful routes on your accounts (ie your users)... but a singular 'feed' resource. 这为您的帐户(即您的用户)提供了通常的RESTful路线......但这是一个单一的“Feed”资源。 You won't need to refer to the id of your feed - but usually just work from the @account.feed 您无需参考Feed的ID - 但通常只需使用@ account.feed即可

use rake routes to show you the full list of routes that this creates. 使用rake routes向您显示此创建的路由的完整列表。

account_feed_path(@account) , for instance will give you the Show page for a feed. 例如, account_feed_path(@account)将为您提供Feed的显示页面。

The paths therefore give you the ability to use form helpers like so: 因此,路径使您能够使用表单助手,如下所示:

<% form_for :feed, account_feed_path(@account) do |f| %>

<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM