views:

18

answers:

1

Hi,

I have a function where I want to show the corresponding value in a select form based on the function below :

 def index
    @initval = Haus.find_all_by_haus_id(1)
  end

It will return a list of value that has haus_id = "1" (so e.g. I will get a, b, c)

in index.rhtml, I want to show the list corresponding to haus_id="1", but showing only their timebuild (so e.g, I will get time of "a" was built, "b" was built, and "c" was built).

<select id="subtable" name="subtable" size="7" style="width: 150px">
    <option selected value="<%= @initval.id %>"><%= @initval.timebuild%></option>
</select>

However, it returns

undefined method `timebuild' for #<Array:0x4b5c238>

If in select form I change @initval.timebuild to @initival.id , it will return a number (that I am not sure where it came from). How can I show a list of timebuild from haus that has haus_id="1" in the select form?

Please kindly guide.

+1  A: 

If you use find_all_by_haus_id the result will be an array of all the matching Haus objects. Even if there is only one matching record it will still be an array with 1 element.

Every object in Ruby has an id method that returns the object's internal ID (although this method name is now deprecated in favour of object_id.) This is the number you are seeing when you call id on your array e.g.

irb(main):002:0> [1, 2, 3].id
(irb):2: warning: Object#id will be deprecated; use Object#object_id
=> 23959200

If you just want to return a single record you can use Haus.find_by_haus_id.

If you do want multiple values then stick with find_all_by_haus_id and use something like options_from_collection_for_select to produce an options tag for each entry.

Finally, if haus_id is the primary key in your table then you can just use find to return the matching object e.g.

@initval = Haus.find(1)
mikej