How do you transform an activerecord attribute from a string to a has_many relationship on reads and writes?
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 开发者_如何学Chave 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?
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
精彩评论