form_for和范围,rails 3 [英] form_for and scopes, rails 3

查看:102
本文介绍了form_for和范围,rails 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于作用域和rails 3中的form_for辅助器,我遇到了问题. 路线-文件如下所示:

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

表单看起来像这样:

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

制表符-属性以字符串形式存储在params [:tab]中 我的问题是,这种形式产生了错误的网址.我怎样才能使它正常工作? 生成的URL article_path(params [:tab],@article)可以很好地工作

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

推荐答案

我想出的答案很丑陋,但同时适用于update和create:

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| %>

更新: 更好的解决方案是将default_url_options-method覆盖为类似以下内容:

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

然后将<%= form_for @article做| f | %>可以使用,并且所有网址均正确生成

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

这篇关于form_for和范围,rails 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆