【问题标题】:Limiting Formtastic collection in a many to many在多对多中限制 Formtastic 集合
【发布时间】:2014-02-22 05:02:42
【问题描述】:

我已经成功地将 formtastic 集成到我的 rails 项目中,并用它在多对多关系中进行多值选择。

问题是我似乎找不到如何将选择限制在相关的范围内。

鉴于以下情况:

class Pool < ActiveRecord::Base
 has_many :poolings, dependent: :destroy
 has_many :commercials, :through => :poolings
 accepts_nested_attributes_for :poolings
 accepts_nested_attributes_for :commercials
 belongs_to :client
end

关系多对多模型

class Pooling < ActiveRecord::Base
 belongs_to :pool
 belongs_to :commercial
end

以及商业模式

class Commercial < ActiveRecord::Base
 belongs_to :client
 has_many :poolings, dependent: :destroy
 has_many :pool, :through => :poolings
end

以下代码用于创建多选表单:

<%= semantic_form_for @pool do |f| %>
  <%= f.inputs %>
  <%= f.inputs :commercials %>
  <%= f.actions %>
<% end %>

关键是假设 :commercials 转换为多对多选择形式。

现在阅读文档,我不明白要添加什么

<%= f.inputs :commercials %>

这样,当我在表单中使用它来编辑“client_id = 1”的“池”时,它只会显示“client_id =1”的“commercials”。

将以下内容与集合选择一起使用会给我预期的结果:

<%= f.collection_select :commercials, Commercial.where(:client_id => @pool.client), :id, :name %>

formtastic 中的等价物是什么?

顺便说一句,作为 RoR 的新手,我发现各种组件和 gem 的处理方式似乎都略有不同,这让我感到非常困惑。开源的乐趣!

【问题讨论】:

    标签: ruby-on-rails-4 has-many-through formtastic


    【解决方案1】:

    有一个用于选择、复选框和单选的“集合”参数(请参阅Usage)。

    对于您的具体问题,解决方案可能如下所示:

    <%= semantic_form_for @pool do |f| %>
      <%= f.inputs do %>
        <%= f.input :commercials, :collection => Commercial.where(:client_id => @pool.client) %>
      <% end %>
      <%= f.actions %>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2011-01-20
      • 2013-01-15
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多