ruby-on-rails - 维特斯 : Replace accepts_nested_attributes (one-to-many) with a form object

标签 ruby-on-rails forms design-patterns object

一个多月以来,我试图了解 Rails 4 中表单对象的 secret 。

使用 virtus ,我已经能够构建非常简单的表单。但是,我未能开发出替代 accepts_nested_attributes_for 的表单对象。 (在模型中)和 fields_for (在表单 View 中)。

this question我解释了一个小电话簿示例:该表单提供了一次输入一个人的姓名和 3 个电话号码的可能性(找到整个代码 here)。

现在我尝试对表单对象做同样的事情。我得到了这个:

# forms/person_form_new.rb
class PersonFormNew
    class PhoneFormNew
        include Virtus

        include ActiveModel::Model

        attr_reader :phone
        attribute :phone_number, String
    end

    include Virtus

    include ActiveModel::Model

    attr_reader :person
    attribute :person_name, String

    attribute :phone, PhoneFormNew

    def persisted?
        false
    end

    def save
        if valid?
            persist
            true
        else
            false
        end
    end

private

    def persist
        @person = Person.create(name: person_name)
        @person.phones.build(:phone)
    end
end

# views/people/new.html.erb
<h1>New Person</h1>

<%= form_for @person_form, url: people_path do |f| %>
    <p>
        <%= f.label :person_name %> </ br>
        <%= f.text_field :person_name %>
    </p>

    <p>
        <%= f.fields_for :phone do |f_pho| %>
            <%= f_pho.label :phone_number %> </ br>
            <%= f_pho.text_field :phone_number %>
        <% end %>

    <p>
        <%= f.submit %>
    </p>
<% end %>

这给了我错误

undefined method `stringify_keys' for :phone:Symbol



线路:@person.phones.build(:phone)
然而,我担心,这不是唯一的错误。

你能指出我用表单对象(最好使用 Virtus)实现一对多赋值的方法吗?

最佳答案

一种解决方案是在表单模型上的单独函数中创建关联对象。通过执行以下操作,我取得了成功:

 def persist!
   @user.save!
   @account.save!
   create_admin_membership
end

def create_admin_membership
  @membership = Membership.create! do |membership|
    membership.user = @user
    membership.account = @account
    membership.admin = true
  end
end

您可以在此处找到扩展说明:http://w3facility.org/question/how-to-create-another-object-when-creating-a-devise-user-from-their-registration-form-in-rails/

关于ruby-on-rails - 维特斯 : Replace accepts_nested_attributes (one-to-many) with a form object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18580406/

相关文章:

ruby-on-rails - Ruby 中的动态验证和元编程

ruby-on-rails - 如何在 Rails 3 中实现批量插入

javascript - 更改 "Choose File"按钮并继续显示文件名

java - 我对如何在我的代码中实现单例模式并让它调用我的对象类和方法感到困惑

ruby-on-rails - 向 iOS 应用程序公开 Rails/Device 身份验证

forms - 最佳实践 : r. PostFormValue ("key") VS r.PostForm.Get ("key")

javascript - 停止 IE10 提交表单

java - 如何在RMI多用户应用程序中实现MVC模式?

c++ - C++中实例变量的算法初始化

ruby-on-rails - 如何覆盖 ruby​​ on rails 4.0.+ 中的默认主键列?