我正在尝试将“自定义字段”添加到销售应用程序(Ruby 2、Rails 4、Postgres)。
这是相关的架构:
执行此操作的最佳方法是什么?values
是多态的,并且与 .fields
是一对多的accounts
。
有没有办法遍历字段并获取相关值?
我正在尝试将“自定义字段”添加到销售应用程序(Ruby 2、Rails 4、Postgres)。
这是相关的架构:
执行此操作的最佳方法是什么?values
是多态的,并且与 .fields
是一对多的accounts
。
有没有办法遍历字段并获取相关值?
我可能弄错了您的问题,但我认为 Rails 正在调用您的whatever-custom-field-label-is
方法,因为它试图获取输入的初始/默认值。
Using the helpers like text_field
requires that there be a getter method for the attribute named. Rails will use that to pre populate the field.
The builtin approach to forms that span multiple models is nested attributes.
If you add accepts_nested_attributes_for :values
to your sale model then
= @sale.fields_for :values do |value_form|
= value_form.label :data, value_form.object.field.label
= value_form.text_field :data
Should render labels and text fields for each of your values (the block will be yielded to once for each value).
Alternatively you could eschew the rails helpers altogether.
If in instead you put in your form
= text_field_tag "sale[values_hash][#{v.field.label}]", v.data
Then it should render with no changes to the model. When the form submits params[:sale][:values_hash]
will be a hash of the field labels to the entered values. You would need a values_hash=
method on your model or the save would blow up. If you continue far enough down this route you'll end up with rails' nested attributes, although this may give you more control.
There are other approaches to complex forms in rails. One is to create form objects who are solely responsible for marshalling data between persistence objects and there form representation, isolating the form from having to know that attribute X is stored in a separate table and that sort of thing