我将一组联接表传递到我的rails选项中,它看起来像这样:
= select_tag :editing_channel, options_from_collection_for_select(@channel_users, :id, :channel_id)
工作正常,但它在视图中显示了channel_id。我想展示频道名称。哪个只是channel.name,我该怎么做呢?
我想显示channel.nae
型号:
class User < ActiveRecord::Base
has_many :channel_users
has_many :channels, through: :channel_users
end
class Channel < ActiveRecord::Base
has_many :channel_users
has_many :users, through: :channel_users
end
答案 0 :(得分:0)
试试这个:
select_tag :editing_channel, options_for_select(@channel_users.map { |cu| [cu.channel.name, cu.id] })
答案 1 :(得分:0)
从API底座:
options_from_collection_for_select(@people, 'id', 'name')
# => <option value="#{person.id}">#{person.name}</option>
在你的情况下它应该是这样的:
= select_tag :editing_channel, options_from_collection_for_select(@channel_users, :id, :name)
答案 2 :(得分:0)
我没有测试过,但试试这个。
在您的视图中使用collection_select
帮助程序,如下所示:
collection_select(:channel_ids, Channel.all, :id, :name)
在User
模型中,请确保已将channel_ids: []
添加到user_params
方法中,以便channel_ids
可以批量分配给用户模型。< / p>