Rapture
Rapture

Reputation: 1896

Date in Text Field with Virtual Attribute

I have already asked a similar question on this, however after seeing the railscast on using textfields - Ryan recommends using a virtual attribute.

I have set up my model with the virtual attribute like so:

attr_accessible :title, :description, :start, :start_string

def start_string
  unless start.nil?
    start.to_s(:db)
  end
end

def start_string(start_str)
  self.start = Date.parse(start_str)
rescue ArgumentError
  @start_invalid = true
end

def validate
  errors.add(:start, "is invalid") if @start_invalid
end

I have included this in my edit view like so:

    <div class="field">
        <%= f.label :start_string %> <br />
        <%= f.text_field :start_string %>
        <%#= f.date_select(:start, :order => [:month, :day, :year], :end_year => Time.now.year + 10) %>
    </div>

However, I get an error when loading my edit form

    wrong number of arguments (0 for 1)

I also know this is a very old railscast and someone event comments:

"As Rayn mentioned if you add nil? check on the getter method it should wotk fine!"

No. The code is outdated for use today. There are more efficient ways to do this now

So what is the proper way to do this now? Seems like an easy and straight forward way to do it...if I wasn't getting an error!

Upvotes: 1

Views: 350

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124439

Your second method should be def start_string=(start_str) (you're missing the equals sign).

Upvotes: 1

Related Questions