0

I am sure I am just doing this wrong, can someone point me in the right direction?

I need to set the value of effective_date to a modified format date

effective_date is an attribute of Request

class Request < ActiveRecord::Base

  def format_date=(format_date)
    date_a = format_date.split("/")
    month, day, year = date_a
    effective_date = Date.parse("#{year}-#{month}-#{day}")
  end

  def format_date
    effective_date
  end
end

Request.create(format_date: "04/21/2012") is not setting the value to effect_date

Edit: I guess this doesn't make sense, so I will try and explain it better:

I need to set the value of effective_date (a column in the database) from format_date (not a column in the database). I am using format_date method to convert the date from format_date and store it into effective_date. If this isn't enough info, let me know. I am not sure what else to add.

Toby Joiner
  • 4,306
  • 7
  • 32
  • 47

2 Answers2

2

If effective_date is the column name in your database, the change is as simple as

def format_date=(format_date)
  date_a = format_date.split("/")
  month, day, year = date_a
  self.effective_date = Date.parse("#{year}-#{month}-#{day}")
end

The only change was effective_date = to self.effective_date =. Without adding self there, there's no way for the interpreter to know whether you want to set a local variable called effective_date or call the effective_date= method. It assumes the local variable.

Emily
  • 17,813
  • 3
  • 43
  • 47
1

If effective_date is attribute but not in the table, then I think you need instance variable.

class Request < AR::Base
  ...
  def format_date=(f_date)
    ...
    @effective_date = Date.parse("#{year}-#{month}-#{day}")
  end

  def format_date
    @effective_date
  end
end

Also, it's not good to use local variable with the name as the name of method (format_date), here's no mistake but it's kinda misleading.

UPDATE: You can see more aboute virtual attributes here:

http://railscasts.com/episodes/16-virtual-attributes?view=asciicast

http://railscasts.com/episodes/167-more-on-virtual-attributes

megas
  • 21,401
  • 12
  • 79
  • 130
  • thanks for the tip on the format_date variable I will change that. I guess I am really making something easy confusing. If I have to make this as easy as possible: I want to be able to have format_date be a text_field in a form. Then I want to convert the date to a usable rails date and store it in the column effective_date in the requests table. format_date does not exist in the table and effective_date does. I might be going about this all wrong and there is a simple answer that I am missing. – Toby Joiner May 01 '12 at 20:32
  • I don't see the mistake, what you're doing is called a virtual attributes, see the update. – megas May 01 '12 at 20:46