Forum: Ruby on Rails Simple question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bob S. (Guest)
on 2006-02-07 20:19
(Received via mailing list)
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/
Jules J. (Guest)
on 2006-02-07 21:01
(Received via mailing list)
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
>removed_email_address@domain.invalid
>http://lists.rubyonrails.org/mailman/listinfo/rails
>


Jules
Jules J. (Guest)
on 2006-02-07 21:01
(Received via mailing list)
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
>removed_email_address@domain.invalid
>http://lists.rubyonrails.org/mailman/listinfo/rails


Jules
This topic is locked and can not be replied to.