Simple question

Looking for the proper/best way to get an attributes value with a
generated
string:

I have fields named with a _1, _2, . etc format and I want to loop
through
them.

10.times do | x |

@model.field_x

end

What is the best way to grab a generated attribute?

I have a feeling its @model.instance_variable_get(“field_#{i}”)

But I think respond_to? And send? Could be used as well.

Thanks for some insight!

Bob S.

http://www.railtie.net/

I think that your database scheme is wrong if you want to do this. You
probably want a has_many for your model. If you have a “Chapter” model
now, and paragraph_1, paragraph_2, etc, then you need a new model
“Paragraph”. And a has_many :paragraphs in your Chapter model.

But if you must use these fields, I would at least abstract it away:

class YourModel
def fields
last_field = 4 # now you have field_1, field_2, field_3, field_4.
(1…last_field).map{|n| send(“field_#{n}”)}
end
end

then you can do:

o = YourModel.find(1)
o.fields.each do |f|
#…
end

But you clearly want a new model…

On Tuesday, February 07, 2006, at 10:17 AM, Bob S. wrote:

10.times do | x |


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

Jules

o, and there is read_attribute() too, if I am not mistaken…

On Tuesday, February 07, 2006, at 6:59 PM, Jules J. wrote:

(1…last_field).map{|n| send(“field_#{n}”)}
But you clearly want a new model…

end

http://www.railtie.net/
Jules


Posted with http://DevLists.com. Sign up and save your time!


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

Jules