1
votes

I am looking to be able have an ActiveRecord object organized like so:

class Job < ActiveRecord::Base
 has_many :lines

  def value
     ..concat lines together separated by \n
  end

  def value=(string)
    lines = string.split( "\n" ).collect do |value|
      Line.new( :text =< value )
    end
  end
end

and would like to have an a from with an text box that points at the :value attribute and be able to call Job.create(form_data) and have rows created in the lines table. Similarly I would like the text box to be filled with data from the value accessor. Is there a simple way to do this?

1

1 Answers

0
votes

It will just work as you described if you do:

in controller:

@job = Job.find(params[:id])

in view:


form_for @job do |f|
  f.label :value
  f.textarea :value
end

and in model:


def value
  lines.map(&:text).join("\n")
end

def value=(v)
  lines.delete
  v.split("\r?\n").each {|line| lines << Line.new(:text=>line)}
end