raails中composition_of聚合属性的simple_form自定义输入

时间:2011-11-15 03:47:55

标签: ruby-on-rails-3 activerecord simple-form

我正在尝试为具有composition_of聚合属性的Rails 3模型的simple_form gem编写自定义输入。请参阅下面的示例。

我尝试使用fields_for,但它会生成像"person"=>{"name"=>{"fname"=>"James","middle"=>"T","lname"=>"Kirk"}这样的参数,它不会被Person.create处理,也不会像关联那样处理update_attributes。

给出以下错误

undefined method `fname' for {"fname"=>"James", "middle"=>"T", "lname"=>"Kirk"}:ActiveSupport::HashWithIndifferentAccess

你会如何实现这个?

实施例

$ rails g scaffold person last_name:string first_name:string middle_name:string

LIB / fullname.rb

class Fullname
  attr_reader :fname, :middle, :lname

  def initialize(fname, middle, lname)
    @fname, @middle, @lname = fname, middle, lname
  end
end    

应用程序/模型/ person.rb

class Person < ActiveRecord::Base
  composed_of :name, 
              :class_name => 'Fullname', 
              :mapping => 
              [ # database      # Fullname
                [:first_name,   :fname], 
                [:middle_name,  :middle], 
                [:last_name,    :lname]
              ],
              :allow_nil => true
end

应用程序/视图/人/ _form.html.haml

= simple_form_for @person do |f|
  = f.input :name, :as => :fullname
  = f.submit 'Save'

应用程序/输入/ fullname_input.rb

class FullnameInput < SimpleForm::Inputs::Base
  def input
    @builder.simple_fields_for attribute_name, :validate => false do |form|
      [   'First:', form.input_field(:fname, :size => 10),
          'Middle:', form.input_field(:middle, :size => 5),
          'Last:', form.input_field(:lname, :size => 10)
      ].join(' ').html_safe
    end
  end
end

0 个答案:

没有答案