简体   繁体   中英

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:

在此处输入图片说明

and I want the name of the temporadas to show.

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'}) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM