Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...