hardow2011
hardow2011

Reputation: 59

How to acces foreign attributes in a select form in Rails?

If I have the models:

class Bloque < ApplicationRecord
  belongs_to :temporada
end

class Temporada < ApplicationRecord
  has_many :bloques
end

And the collection_select in a view:

<%= collection_select(:bloques, :id, Bloque.all, :id, :temporada, {}, {class: 'form-control', multiple: 'true'}) %>

I want the name of temporada in Bloque, as in :temporada_name, instead of plain :temporada in the collection_select. Because the list appears as:

enter image description here

and I want the name of the temporadas to show.

Upvotes: 0

Views: 31

Answers (1)

max
max

Reputation: 101811

Use Module#delegate to delegate temporada_name to temporada.name.

class Bloque < ApplicationRecord
  belongs_to :temporada
  delegate :name, to: :temporada, prefix: true
end

<%= collection_select(:bloques, :id, Bloque.includes(:temporada).all, :id, :temporada_name, {}, {class: 'form-control', multiple: 'true'}) %>

Upvotes: 1

Related Questions