Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

form_for and scopes, rails 3

I have a problem due to scopes and the form_for helper in rails 3. The routes - file looks like this:

scope "(/:tab)" do
  resources :article
end

The form looks something like this:

<%= form_for(@article) %>
   <%= f.label :title %>
   <%= f.text_field :title %>
    etc.
<%end%>

The tab - attribute is stored in params[:tab], as a string My problem is that this genereate wrong urls in the form. How could I get this to work ? The genreated url article_path(params[:tab], @article) works perfectly fine

like image 401
iverds Avatar asked Sep 18 '10 14:09

iverds


3 Answers

The answer I came up with was quite ugly, but works with both update and create:

<%= form_for(@article, :url => (@article.new_record? ? 
    articles_path(params[:tab]) : article_path(params[:tab], @article) do |f| %>

Update: A better solution would be to override the default_url_options-method to something like this:

def default_url_options(options={})
  { :tab => params[:tab] }
end

Then the <%= form_for @article do |f| %> could be used, and all urls are correctly generated

like image 131
iverds Avatar answered Sep 23 '22 11:09

iverds


Try:

<%= form_for [:tab, @article] do |f| %>
   <%= f.label :title %>
   <%= f.text_field :title %>
    etc.
<%end%>
like image 26
Yannis Avatar answered Sep 20 '22 11:09

Yannis


You could specify the path explicitly:

<%= form_for(@article, :url => article_path(@article, :tab => params[:tab]) %>
like image 38
Matt Haley Avatar answered Sep 22 '22 11:09

Matt Haley