Reputation: 11865
I have form fields from one model status_history
that I am including in my member
edit. I am wanting to make it so that if the fields for status_history are empty, then it will not save. Currently it is saving blank items to status_history
when I save a members
edit.
My member
form looks like this
form(:html => { :multipart => true }) do |f|
f.semantic_errors *f.object.errors.keys
columns do
column do
...
end
column do
f.inputs "Status" do
f.semantic_fields_for :status_histories, StatusHistory.new do |sh|
sh.inputs :class => "" do
sh.input :status, as: :select, collection: {Active: "active", Inactive: "inactive", Separated: "separated"}
sh.input :date, :as => :datepicker
sh.input :reason
end
end
table_for member.status_histories do
column "status" do |status_histories|
status_histories.status
end
column "date" do |status_histories|
status_histories.date
end
column "reason" do |status_histories|
status_histories.reason
end
end
end
...
end
end
f.actions
end
models/status_histories
class StatusHistory < ActiveRecord::Base
belongs_to :member
STATUS_TYPES = [ "active", "inactive", "separated" ]
validates :status, inclusion: STATUS_TYPES
validates :date, :presence => true
validates :reason, :presence => true
end
Even adding a button that would toggle the semantic_fields_for would work but currently if I leave them blank I get validates
errors.
How would I override the save method to check if status and date are present and if so save the status_history
and if not, do not save the status_history
but save the rest of the member
fields?
Upvotes: 0
Views: 2783
Reputation: 2970
Try this:
in Member
ActiveRecord model
accept_nested_attributes_for :status_histories, reject_if: :all_blank
http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for
Upvotes: 1