Thanks to Rails Formtastic: adding "data-" field to option tag I got an easy solution to adding a data fieed to options in my ActiveAdmin form. But, now I want to get the data value from a different table (model). I'm a total rails newbie, trying to figure things out as I go, hoping someone can steer me right on this.
So, I have this in my ActiveAdmin form:
att.input :attribute, :label => "Attribute:", :as => :select, :collection => AttributeDefinition.all.map { |adef| [adef.attribute_name, adef.id, {:"data-type" => AttributeInputType.where(:id => adef.input_type_id).select("input_type") } ] }
What I'm hoping to end up with is a select element with options like this:
<option data-type="dropdown" value="4">Voltage</option>
But instead, I am getting options like this:
<option data-type="#<ActiveRecord::Relation:0x6adb3f8>" value="4">Voltage</option>
This is for a Product model, which has_many :attribute_definitions, through: :product_attributes
, and each AttributeDefinition belongs_to :input_type, class_name: "AttributeInputType"
. So I am trying to reach the input_Type field (string) of the AtributeInputType which matches the input_type_id of the AttributeDefinition (adef.input_type_id
above).
I can get the ID, and the data-type attribute is generated ok, so I think my problem is just basic not knowing how to pull that string field by ID. Anyone can point me in the right direction? Thanks!
replace this
AttributeInputType.where(:id => adef.input_type_id).select("input_type")
with
adef.input_type.input_type
adef.input_type
returns the AttributeInputType
object associated with adef
. .input_type
returns the input_type
attribute of the AttributeInputType
object.
In case adef
does not have any input_type
the above statement would throw an error. So a more robust option is
adef.input_type.try(:input_type)
try
returns nil
if the associated object is not found.