Controller edit method, modify object data before commit
When a user saves a form, I want to do the following check before saving
if header2 is null
header2 = header1
I don't want to add validation and stop the save action, because header2 is only needed in rare occasions. I'm not sure how to have the update method in the controller do this. The command to commi开发者_JS百科t the update is
if @entry.update_attributes(params[:entry])
So should I be modifying the params[:entry][:header2] field? I tried to do this with the following code but it isn't updating
params[:entry][:header2] = params[:entry][:header1]
Any help would be appreciated. I'm starting to feel I should handle this on the client side with javascript instead.
--EDIT: Added to original Post Below--
I have tried coderama's suggestions below and neither work for me
validate :data_present
def data_present
self.header2 = self.header1 if self.header2 == nil
end
and
def update
@entry = Entry.find(params[:id])
params[:entry][:header2] = params[:entry][:header1] unless params[:entry][:header2].present?
respond_to do |format|
if @entry.update_attributes(params[:entry])....
SQL
mysql> select header1, header2 from entries where title = "new";
+---------+---------+
| header1 | header2 |
+---------+---------+
| Blah | NULL |
+---------+---------+
1 row in set (0.00 sec)
I want be able to open in edit mode, change nothing (field is already null) and hit save and have this code changed. Have also tried for making new entry records and it doesn't work there either.
Here you go, along with the specs to prove
/app/models/model_name.rb
class ModelName < ActiveRecord::Base
attr_accessor :header_1, :header_2
before_validation :header_check
def header_check
return if self.header_2.blank?
self.header_1 = self.header_2 if self.header_1.blank?
end
end
And the spec: /spec/models/model_name_spec.rb
require 'spec_helper'
describe ModelName do
before(:each) do
@model_name = ModelName.new
@header_one_text = "HeaderOneText"
@header_two_text = "HeaderTwoText"
end
it "should should set header 2 if header 1 is blank" do
@model_name.header_2 = @header_two_text
@model_name.valid?
@model_name.header_1.should == @header_two_text
end
it "should leave header 1 if both are set" do
@model_name.header_1 = @header_one_text
@model_name.header_2 = @header_two_text
@model_name.valid?
@model_name.header_1.should == @header_one_text
end
end
Addressing your own options, these could be possible solutions which I have both used successfully depending on my circumstances.
Option 1 - Model Validation
Create a custom validation or a validation based on a condition. E.g.
class Body < ActiveRecord::Base
validates_presence_of :hair, :unless => lambda { |o| o.age > 80 }
validate :multiple_heads
def multiple_heads
self.head = "No head" if self.head == nil
end
end
Option 2 - Modify the hash in the controller
Your second suggestion will also work. E.g.
params[:entry][:header2] = params[:entry][:header1] unless params[:entry][:header2].present?
精彩评论