Sreeraj Chundayil
Sreeraj Chundayil

Reputation: 5859

simple_form with two models?

This is my creation form for Customer model.

While populating customers table I am inserting some data in managers table as well. But I want to add a date picker in this simple_form but that date is only stored in Manger model and Customer model doesn't have date field. How do I do it? What alternative options I have?

new.html.erb

<%= stylesheet_link_tag "customers" %>
  <div class="row">
    <div class="panel panel-default center" id="new-width">
      <div class="panel-body">
        <%= simple_form_for @customer do |f| %>
          <%= f.input :name,:autocomplete => :off %>
          <%= f.input :principalAmount,:autocomplete => :off %>
          <%= f.input :interestRate %>
          <%= f.input :accountType %>
          <%= f.input :duration,:autocomplete => :off %>
          <%= f.button :submit %>
        <% end %>
      </div>
    </div>
</div>

Edit: Manager model has many field which is independent of Customer model. But When a customer is created it has to add a date in Manager model which is absent in the Customer model.

Upvotes: 0

Views: 1231

Answers (2)

Dhanabal
Dhanabal

Reputation: 121

I suggest you to use accepts_nested_attributes_for in customers model. Something like this:

In customer model,

accepts_nested_attributes_for :managers

In view page,inside the existing form

<%= f.fields_for :managers do |m| %>
    <%= m.date_field :date %>
<% end %>

Upvotes: 2

Mark Swardstrom
Mark Swardstrom

Reputation: 18070

You can always add a getter and setter to the customer model and manually set the manager fields. Again it depends on the relationship with manager, if it exists already, etc. but the main point is you can create methods that can then be accessed in the form as customer methods.

# in customer.rb

def manager_date=(date)
  manager.date = date
end

def manager_date
  manager.date
end

then in the form

<%= f.input :manager_date %>

Note - this is a brief example, you'll need to save the manager somewhere and doing this before or after the customer is updated will depend on your needs.

Another way to do this is to create an attr_accessor for manager_date in customer and if it's there, update the manager after the customer is saved

after_save :update_manager

def update_manager
  manager.date = manager_date
  manager.save
end

Upvotes: 2

Related Questions