2

我正在尝试获取 grouped_collection_select 的记录子集,在模式中我有一个品牌和一个模型,我们处理不同的产品线,当我们请求产品时,我们指定我们要请求的线,所以,我们可以有品牌,以及那条线的模型,所以模型定义如下:

品牌模型

class Brand < ActiveRecord::Base
  validates :brand_key, uniqueness: true, presence:true
  has_many :models
  accepts_nested_attributes_for :models, allow_destroy: true
end

Modelx 型号

class Modelx < ActiveRecord::Base
  belongs_to :brand
  belongs_to :line
  validates :model_key, uniqueness: true, presence:true
end

线型

class Line < ActiveRecord::Base
  validates :line_key, uniqueness: true, presence:true, length: {in: 1..6}
  has_many :line_features, -> { order(:sort_order) }
  has_many :modelx
  accepts_nested_attributes_for :line_features, allow_destroy: true
end

产品型号

class Product < ActiveRecord::Base
  belongs_to :vendor
  belongs_to :line
  belongs_to :brand
  belongs_to :modelx
  belongs_to :operating_status
  has_many :line_features, -> { order(:sort_order)}

  store_accessor :line_features
end

产品控制器(新)

def new
  @brands=brand.where(id: Modelx.select(:brand_id).where(line_id: params[:line_id]))
  @modelxs=Modelx.where(line_id: params[:line_id])
  ...
end

部分形式的摘录

<%= f.collection_select( :brand_id, @brands, :id, :brand,{:prompt =>'Brands'}) %>
<%= f.grouped_collection_select(:modelx_id, @brands, :modelx, :brand, :id, :modelox) %>

现在,我面临的问题是,当我展示一个模型时,我只需要展示该品牌和产品线可用的模型,但是,请求是为该品牌提供所有模型,而我没有'不知道如何区分那些不需要的行。

非常感谢任何帮助、提示或建议。

更新问题

我不知道这是解决方法还是问题的解决方案,但是,这是我找到解决要求的唯一方法,因此我将其发布为更新而不是回答对谁有帮助的问题。

  1. 再次查看文档,发现所:modelx引用的方法<%= f.grouped_collection_select(:modelx_id, @brands, :modelx, :brand, :id, :modelox) %>是请求所有模型,如apidock中所述,这种方法是解决问题的方法。

  2. 根据上面描述的子集在品牌模型中创建了一个方法,由于分组是按品牌进行的,这里摘录

品牌模型(摘录)

  ...
  def modelx_ltvi
    Modelx.where("line_id = ? and brand_id =?",$line_id, self.id)
  end

特别注意:由于我的经验不足,我无法从表单中传递 :line_id 的值,所以我把它放在了一个全局变量中。

  1. 修改了部分表单

部分形式的摘录

 ...
<%  $line_id=@product.line_id %> 
 ...
<%= f.grouped_collection_select(:modelx_id,
      @brands, :modelx_ltvi, :brand, 
      :id, :modelx) %>
  <% end %>

这会让仓鼠跑起来。

4

1 回答 1

0

按您刚刚找到的品牌过滤您的模型,例如:

@brands=Brand.where(id: Modelx.select(:brand_id).where(line_id: params[:line_id]))
@modelxs=Modelx.where(line_id: params[:line_id], brand_id:  @brands.map(&:id))
@selected_model_names = @modelxs.map(&:name).sort.uniq
于 2016-04-16T23:05:48.820 回答