Bind simple_form in non-activerecord class? Is it possible?

1,018 views
Skip to first unread message

Pablo Cantero

unread,
Dec 12, 2011, 3:39:51 PM12/12/11
to SimpleForm
Hello

I'm creating a search form to retrieve publishers created_at between
start_date and end_date.

<%= simple_form_for @publisher_criteria, :url =>
publisher_reports_path, :html => {:method => :get} do |f| %>
<%= f.input :start_date, :as => :date, :include_blank => true %>
<%= f.input :end_date, :as => :date, :include_blank => true %>
<%= f.submit :value => t("commons.search"), :class => "btn" %>
<% end %>

It doesn't work in this way, because Publisher model hasn't start_date
and end_date attributes. I tried to create to create a simple classe

class PublisherCriteria
attr_accessor :start_date
attr_accessor: end_date
end

But it seems that simple_form needs an ActiveRecord Model to bind
properly.

I used a dirty workaround to solve it

(@publisher_criteria instance of Publisher < ActiveRecord::Base)

<%= simple_form_for @publisher_criteria, :url =>
publisher_reports_path, :html => {:method => :get} do |f| %>
<%= f.input :created_at, :as => :date, :include_blank => true %>
<%= f.input :updated_at, :as => :date, :include_blank => true %>
<%= f.submit :value => t("commons.search"), :class => "btn" %>
<% end %>

in the controller

criteria = ["created_at >= ? and created_at <= ?",
@publisher_criteria.created_at, @publisher_criteria.updated_at]
@publishers = @partner.publishers.where(criteria).all

What is the best approach to do it with simple_form/rails
architecture?

Cheers,
Pablo Cantero

Rafael Mendonça França

unread,
Dec 18, 2011, 1:11:41 PM12/18/11
to plataformate...@googlegroups.com
Yes, you can bind non-activerecord classes to rails forms.

The best way to do this is implementing the ActiveModel API to Naming and Conversion.

You can see how we do this on the SimpleForm tests in this file.
Reply all
Reply to author
Forward
0 new messages