【问题标题】:How can I generate a route for a form helper with a has_one relationship?如何为具有 has_one 关系的表单助手生成路由?
【发布时间】:2014-02-04 01:34:56
【问题描述】:

User has_one Subscription

在 config/routes.rb 中:

resources :users do
  member do
    resource :subscription, controller: :subscription
  end
end

我知道那可能是错的。

表单助手:

<%= simple_form_for [@user,@subscription] do |f| %>

但这种格式基本上假定has_many 关系,我得到这个错误:

ActionView::Template::Error (undefined method `user_subscriptions_path' for #<#<Class:0x007f8066709020>:0x007f8066717670>):

那我试试这个,比较接近:

<%= simple_form_for @subscription, html: { id: "new_subscription", class: 'form-horizontal' }, defaults: { label_html: { style: "float:left;" } } do |f| %>

但结果是:

ActionView::Template::Error (undefined method `subscriptions_path' for #<#<Class:0x007f8066709020>:0x007f806d57de20>):

感谢您提供的任何帮助。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    看来你需要在 simple_form 插件中使用singular 关系:

    # User.rb
    class User < ActiveRecord::Base
      has_one :subscription
      accepts_nested_attributes_for :subscription
    end
    

    【讨论】:

    • 这不是我真正想要的安迪。我的用户已经创建,这是一个订阅页面。如果我在一个页面上完成注册,我将朝着这个方向前进。我实际上是在尝试将其分解为谨慎的步骤,以使屏幕更简单。但是你给了我一个关于我遇到的另一个问题的想法,谢谢你的帮助。更新:请看我刚刚发布的答案。
    • 啊,我明白了。有没有办法实现 [custom_form_for][cff] 并将用户作为关系传递?抱歉,我已经有好几年没有进行积极的 RoR 开发了。 [cff]:github.com/plataformatec/simple_form#custom-form-builder
    【解决方案2】:

    答案就在here。但是不要看公认的答案,看看下面标题为Where does that magic path come from? 的经过广泛研究的答案。这才是最重要的,同时让您深入了解 Rails 的基础。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多