【问题标题】:edit/update collection_select with has-many-through association使用 has-many-through 关联编辑/更新 collection_select
【发布时间】:2014-04-15 21:10:20
【问题描述】:

我有以下模型:RECIPE、TAG 和 TAGGING(连接表)

食谱.rb

has_many :taggings
has_many :tags, through: :taggings
accepts_nested_attributes_for :taggings

标签.rb

has_many :taggings
has_many :recipes, through: :taggings

scope :diet, -> { where(type_id: 1).to_a }
scope :category, -> { where(type_id: 2).to_a }
scope :festivity, -> { where(type_id: 3).to_a }
scope :daily, -> { where(type_id: 4).to_a }

到目前为止一切正常。但是,在我的 TAGS 表中,我有一个名为“type_id”的字段,它为我带来了一种标签分类。所以我创建了一些“范围”来区分彼此。

tagging.rb

belongs_to :recipe
belongs_to :tag, :counter_cache => :recipes_count

recipes_controller.rb

def new
    @recipe = Recipe.new
    @recipe.tags.build
    @recipe.taggings.build(:recipe => @recipe)
end

def edit
end

我的表格

= f.fields_for :taggings, @recipe.taggings.build do |builder| 
    = builder.collection_select :tag_id, Tag.diet, :id, :name

= f.fields_for :taggings, @recipe.taggings.build do |builder| 
    = builder.collection_select :tag_id, Tag.category, :id, :name

= f.fields_for :taggings, @recipe.taggings.build do |builder| 
    = builder.collection_select :tag_id, Tag.festivity, :id, :name

= f.fields_for :taggings, @recipe.taggings.build do |builder| 
    = builder.collection_select :tag_id, Tag.daily, :id, :name

当我创建一个新配方时,标签通常会添加到连接表(标签)中。但是当我编辑 collection_select 帮助器时,并没有将项目标记为“已选择”。

如何构造多范围的collection_select?

如何为 EDIT/UPDATE 操作构造 collection_select?

还有其他更好的方法吗?

【问题讨论】:

    标签: sql ruby-on-rails ruby-on-rails-4 many-to-many has-many-through


    【解决方案1】:

    它对我有用:

    = f.fields_for :taggings, @recipe.taggings.order("id").first do |diet|
        = diet.collection_select :tag_id, Tag.diet, :id, :name
    
    = f.fields_for :taggings, @recipe.taggings.order("id").second do |category| 
        = category.collection_select :tag_id, Tag.category, :id, :name
    
    = f.fields_for :taggings, @recipe.taggings.order("id").third do |festivity| 
        = festivity.collection_select :tag_id, Tag.festivity, :id, :name
    
    = f.fields_for :taggings, @recipe.taggings.order("id").fourth do |daily| 
        = daily.collection_select :tag_id, Tag.daily, :id, :name
    

    【讨论】:

      【解决方案2】:

      试试

      = f.fields_for :taggings, @recipe.taggings do |builder| 
      

      代替

      = f.fields_for :taggings, @recipe.taggings.build do |builder| 
      

      因为您每次都返回新标签,而不是重复使用之前创建的标签。

      【讨论】:

      • 感谢@MarcAlexandreBerube,但它对我不起作用。我认为问题在于我的范围。您的回答(我已经尝试过)只给我带来了一个范围。我将标签分为 4 个不同的范围:Tag.diet、Tag.category、Tag.festivity、Tag.daily。我不能将所有类型的标签放在同一个地方。你能理解我吗? obs.:对不起我的英语!
      猜你喜欢
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      相关资源
      最近更新 更多