Topic: Can I improve my design?

Hi all,
I have date of birth of users saved in db. In the view page, The date is converted to select list using the select_date tag, like shown below.

<%= select_date @user.dob.to_date, :prefix => 'dob', :start_year =>

1920,  :use_month_numbers => true %>
I'm using the following code in my controller to save the changes made in the list using the following code.
  @dobyyear = params[:dob][:year]
  @dobmonth = params[:dob][:month]
  @dobday = params[:dob][:day]
  @dob = @dobmonth.to_s + "/" + @dobday.to_s + "/" + @dobyyear.to_s
  person.dob = @dob
  person.save
  person.update_attributes(params[:person])

Note: There are text fields, that's why the update_attributes

The question is that, even though the code is working right I feel I'm making code so complex. I believe that there is an easy way for this. Can any one advice me on that. Also do I really need a .save and update_attibutes code?
Thanks
Chris.

Last edited by chryste (2007-07-21 03:00:35)

Re: Can I improve my design?

In general you should try not to have any business logic, i.e. the code you use to work out the dob attribute, in your controller. This should go in your model instead.

I think in this case though rails should work out the correct dob attribute for you so you shouldn't even need,
<pre>
   @dobyyear = params[:dob][:year]
   @dobmonth = params[:dob][:month]
   @dobday = params[:dob][:day]
   @dob = @dobmonth.to_s + "/" + @dobday.to_s + "/" + @dobyyear.to_s
</pre>

What happens if you just use:
<pre>
   def update
     @person = Person.find(params[:person][:id])
     @person.attributes = params[:person]
    etc.

   end

</pre>

Last edited by Tommas (2007-07-21 07:09:06)

Re: Can I improve my design?

you could push the whole logic of creating the Dob into the model ...

# Model
class Person
  attr_accessor :year, :month, :day
  before_save :create_dob

private

def create_dob
  self.dob = self.month + "/" + self.day + "/" + self.year
end
end

#controller:
@person = Person.find() # find the person by id, whereever in your params has it is saved (you know this part  wink
@person.update_attributes(params[:person]


That's basically it.

before #update_attributes saves the record, #create_dob Method will be called in the model. this will create the correct dob, and then the record gets saved.
Code untested, but *should* work

Re: Can I improve my design?

Thanks Duplex,
I believe your solution is fine, but when I implement I'm not grtting the results. It may be the other pieces of code. So I'll check my code and rectify.
Thanks for the idea.
Chris

Re: Can I improve my design?

Personally I would use virtual attributes. Theres no point me explaining them when there is a beautiful screencast by ryan showing you them.

Virtual attributes a simpler version of Duplex's method, it just eliminates the need to have a :before_save callback. Well thats what I believe anyway, feel free to correct me.

Sam