2014-04-01 38 views
1

我正在使用ActiveModel創建一個非模型對象,該對象將與Rails表單構建器一起使用。這是一個Rails 3項目。這裏是我到目前爲止的一個例子:如何處理非模型Rails表單中的日期字段?

class SalesReport 
    include ActiveModel::Validations 
    include ActiveModel::Conversion 
    extend ActiveModel::Naming 

    attr_accessor :promotion_code, :start_date, :end_date 

    def initialize(attributes = {}) 
    attributes.each do |name, value| 
     send("#{name}=", value) 
    end 
    end 

    def persisted? 
    false 
    end 
end 

我碰巧使用HAML和simple_form,但這並不重要。最終,我只是用標準的Rails日期選擇字段:

= simple_form_for [:admin, @report], as: :report, url: admin_reports_path do |f| 
    = f.input :promotion_code, label: 'Promo Code' 
    = f.input :start_date, as: :date 
    = f.input :end_date, as: :date 
    = f.button :submit 

Rails的分裂了日期字段分成單獨的域,所以在提交表單的時候,實際上是被提交3個日期字段:

{ 
    "report" => { 
    "start_date(1i)" => "2014", 
    "start_date(2i)" => "4", 
    "start_date(3i)" => "1" 
    } 
} 

在我SalesReport對象,我分配PARAMS我attr方法,但我發現,我沒有start_date(1i)=方法,我顯然還沒有定義的錯誤。最終,我想結束一個Date對象,我可以使用它來代替3個單獨的字段。

我應該如何在非模型對象中處理這些日期字段?

回答

3

在初始化過程中,您可以手動將屬性中的值分配給類方法,並在下方覆蓋您的設置方法start_dateend_date

class SalesReport 
    include ActiveModel::Validations 
    include ActiveModel::Conversion 
    extend ActiveModel::Naming 

    attr_accessor :promotion_code, :start_date, :end_date 

    def initialize(attributes = {}) 
    @promotion_code = attributes['promotion_code'] 
    year = attributes['start_date(1i)'] 
    month = attributes['start_date(2i)'] 
    day = attributes['start_date(3i)'] 
    self.start_date = [year, month, day] 
    end 

    def start_date=(value) 
    if value.is_a?(Array) 
     @start_date = Date.new(value[0].to_i, value[1].to_i, value[2].to_i) 
    else 
     @start_date = value 
    end 
    end 

    def persisted? 
    false 
    end 
end 

這應該允許你給二傳手一個Date實例或Array與獨立日期元素和setter方法的正確日期分配到@start_date。 只需要爲@end_date做同樣的事情。

希望這可以幫助你。

相關問題