7

由于范围和 rails 3 中的 form_for 助手,我遇到了问题。路线 - 文件如下所示:

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

表单看起来像这样:

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

tab - 属性存储在 params[:tab] 中,作为字符串我的问题是这会在表单中生成错误的 url。我怎样才能让它工作?类型化的 url article_path(params[:tab], @article) 工作得很好

4

7 回答 7

12

我想出的答案非常丑陋,但适用于更新和创建:

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

更新:更好的解决方案是将 default_url_options-method 覆盖为如下所示:

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

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

于 2010-11-07T14:40:57.890 回答
10

尝试:

<%= form_for [:tab, @article] do |f| %>
   <%= f.label :title %>
   <%= f.text_field :title %>
    etc.
<%end%>
于 2010-09-19T07:16:26.300 回答
1

您可以明确指定路径:

<%= form_for(@article, :url => article_path(@article, :tab => params[:tab]) %>
于 2010-09-18T23:02:17.090 回答
1

我对form_for 和 scopes的类似问题的解决方案是在 中定义新方法helpers/<model_name>/<model_name>_helper.rb,例如我的是 sessions_helper.rb 其中包含

module Implant::SessionsHelper
  def sessions_form_path(session)
    session.new_record? ? sessions_path : session_path(session)
  end
end

在我看来,我做了

form_for(@session, url: sessions_form_path(@session)) do |f|

有问题的 routes.rb 部分

scope module: 'implant' do
  resources :sessions
end

...并且要使用:tab参数进行管理,您可以将其添加到辅助方法中。

于 2016-07-19T14:12:38.380 回答
0

我发现这是一个非常烦人的问题,并且现在已经通过以下猴子补丁解决了这个问题。像这样的通用,它有点出价,因为你只是将整个参数包传递给 polymorphic_url ,这是 form_for 在引擎盖下使用来猜测路线。更简洁的方法是仅合并范围值。

我的解决方案:

https://gist.github.com/1848467

module ActionDispatch
  module Routing
    module PolymorphicRoutes
      def polymorphic_path(record_or_hash_or_array, options = {})
        begin
            polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path))
        rescue Exception => e
            polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path).merge(params.reject{|k,v| ["controller", "action"].include? k.to_s}))
        end
      end
    end
  end
end
于 2012-02-16T22:52:12.740 回答
0

在非常相似的情况下,我在如下路线中定义了范围:

scope :path => ":election_id", :as => "election" do 
  resources :questions
end

现在我有像这样的帮手election_questions_path(@election)

在我可以使用的表格中:

form_for [@election, @question] do |f|
  ...
end

在上面的示例@election中是选举模型的一个实例。

将 Friendly_id 集成到此解决方案中后,我得到了一些漂亮的网址。例如“http://mydomain.com/elections-2012/questions/my-question”

于 2012-09-09T19:02:00.863 回答
0

I'm not sure how far back this goes, but it works on Rails 6. I use:

<%= form_for(@article, url: [@article, { tab: params[:tab] }]) %>
   <%= f.label :title %>
   <%= f.text_field :title %>
    etc.
<% end %>

This works because of the array URL generation syntax. In the new case, @article is detected as not being persisted and routes to the POST route. In the edit case, @article is detected as being persisted and routes to the PUT route with the ID.

于 2020-10-22T13:50:45.273 回答