Monday, November 7, 2022

[FIXED] How do I make RoR select option name and id concatenations of other fields?

Issue

I”m using Rails 4.2.3. I have a relation that returns certain columns …

MyObject.joins(:distance_unit)
    .where(["user_id = ?", user.id])
    .select("distance, distance_units.id, distance_units.abbrev")

This data is meant to be used in a select menu …

<%= select_tag "distance", options_from_collection_for_select(@distance_options, "distance", "distance") %>

However, what I want is for the id to be a concatenation of the “distance” and “distance_units.id” fields and the option name to be a concatenation of the “distance” and “distance_unit.abbrev” fields. How do I do that in Rails?


Solution

  • You can do it with options_for_select, like this:

    <%= select_tag "distance", options_for_select(@distance_options.collect{|obj| ["#{obj.distance}_#{obj.id}", "#{obj.distance}_#{obj.abbrev}"]}) %>
    


Answered By - Devd
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.