Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 796
Brian Armstrong Avatar asked Jul 21 '09 06:07

Brian Armstrong


2 Answers

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.

like image 131
graywh Avatar answered Nov 05 '22 12:11

graywh


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?

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. That gives you the usual RESTful routes on your accounts (i.e. your users)... but a singular 'feed' resource. You won't need to refer to the id of your feed - but usually just work from the @account.feed

use rake routes to show you the full list of routes that this creates.

account_feed_path(@account), for instance will give you the Show page for a feed.

The paths therefore give you the ability to use form helpers like so:

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

<% end %>
like image 25
mylescarrick Avatar answered Nov 05 '22 13:11

mylescarrick