Rails has_many 通过表单,在连接模型中带有复选框和额外字段

发布于 2025-01-03 09:20:49 字数 1048 浏览 1 评论 0原文

我正在尝试解决一个非常常见的(正如我所想的)任务。

共有三种模型:

class Product < ActiveRecord::Base  
  validates :name, presence: true

  has_many :categorizations
  has_many :categories, :through => :categorizations

  accepts_nested_attributes_for :categorizations
end

class Categorization < ActiveRecord::Base
  belongs_to :product
  belongs_to :category

  validates :description, presence: true # note the additional field here
end

class Category < ActiveRecord::Base
  validates :name, presence: true
end

当涉及到产品新建/编辑表单时,我的问题就开始了。

创建产品时,我需要检查它所属的类别(通过复选框)。我知道可以通过创建名称如“product[category_ids][]”的复选框来完成。但我还需要输入每个已检查关系的描述,该描述将存储在连接模型(分类)中。

我在复杂的表单、habtm 复选框等上看到了那些漂亮的 Railscast。我几乎一直在 StackOverflow 上搜索。但我还没有成功。

我发现一篇帖子描述了与我几乎完全相同的问题。最后一个答案对我来说有一定意义(看起来这是正确的方法)。但它实际上并不能很好地工作(即如果验证失败)。我希望类别始终以相同的顺序显示(以新/编辑表单;验证之前/之后),并且复选框在验证失败时保持在原来的位置,等等。

任何想法都值得赞赏。 我是 Rails 新手(从 CakePHP 切换过来),所以请耐心等待并尽可能详细地写。请指出我正确的方法!

谢谢。 :)

I'm trying to solve a pretty common (as I thought) task.

There're three models:

class Product < ActiveRecord::Base  
  validates :name, presence: true

  has_many :categorizations
  has_many :categories, :through => :categorizations

  accepts_nested_attributes_for :categorizations
end

class Categorization < ActiveRecord::Base
  belongs_to :product
  belongs_to :category

  validates :description, presence: true # note the additional field here
end

class Category < ActiveRecord::Base
  validates :name, presence: true
end

My problems begin when it comes to Product new/edit form.

When creating a product I need to check categories (via checkboxes) which it belongs to. I know it can be done by creating checkboxes with name like 'product[category_ids][]'. But I also need to enter a description for each of checked relations which will be stored in the join model (Categorization).

I saw those beautiful Railscasts on complex forms, habtm checkboxes, etc. I've been searching StackOverflow hardly. But I haven't succeeded.

I found one post which describes almost exactly the same problem as mine. And the last answer makes some sense to me (looks like it is the right way to go). But it's not actually working well (i.e. if validation fails). I want categories to be displayed always in the same order (in new/edit forms; before/after validation) and checkboxes to stay where they were if validation fails, etc.

Any thougts appreciated.
I'm new to Rails (switching from CakePHP) so please be patient and write as detailed as possible. Please point me in the right way!

Thank you. : )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

墨离汐 2025-01-10 09:20:49

看来我想通了!这是我得到的:

我的模型:

class Product < ActiveRecord::Base
  has_many :categorizations, dependent: :destroy
  has_many :categories, through: :categorizations

  accepts_nested_attributes_for :categorizations, allow_destroy: true

  validates :name, presence: true

  def initialized_categorizations # this is the key method
    [].tap do |o|
      Category.all.each do |category|
        if c = categorizations.find { |c| c.category_id == category.id }
          o << c.tap { |c| c.enable ||= true }
        else
          o << Categorization.new(category: category)
        end
      end
    end
  end

end

class Category < ActiveRecord::Base
  has_many :categorizations, dependent: :destroy
  has_many :products, through: :categorizations

  validates :name, presence: true
end

class Categorization < ActiveRecord::Base
  belongs_to :product
  belongs_to :category

  validates :description, presence: true

  attr_accessor :enable # nice little thingy here
end

形式:

<%= form_for(@product) do |f| %>
  ...
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>

  <%= f.fields_for :categorizations, @product.initialized_categorizations do |builder| %>
    <% category = builder.object.category %>
    <%= builder.hidden_field :category_id %>

    <div class="field">
      <%= builder.label :enable, category.name %>
      <%= builder.check_box :enable %>
    </div>

    <div class="field">
      <%= builder.label :description %><br />
      <%= builder.text_field :description %>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

和控制器:

class ProductsController < ApplicationController
  # use `before_action` instead of `before_filter` if you are using rails 5+ and above, because `before_filter` has been deprecated/removed in those versions of rails.
  before_filter :process_categorizations_attrs, only: [:create, :update]

  def process_categorizations_attrs
    params[:product][:categorizations_attributes].values.each do |cat_attr|
      cat_attr[:_destroy] = true if cat_attr[:enable] != '1'
    end
  end

  ...

  # all the rest is a standard scaffolded code

end

乍一看它工作得很好。我希望它不会以某种方式损坏..:)

谢谢大家。特别感谢 Sandip Ransing 参与讨论。我希望它对像我这样的人有用。

Looks like I figured it out! Here's what I got:

My models:

class Product < ActiveRecord::Base
  has_many :categorizations, dependent: :destroy
  has_many :categories, through: :categorizations

  accepts_nested_attributes_for :categorizations, allow_destroy: true

  validates :name, presence: true

  def initialized_categorizations # this is the key method
    [].tap do |o|
      Category.all.each do |category|
        if c = categorizations.find { |c| c.category_id == category.id }
          o << c.tap { |c| c.enable ||= true }
        else
          o << Categorization.new(category: category)
        end
      end
    end
  end

end

class Category < ActiveRecord::Base
  has_many :categorizations, dependent: :destroy
  has_many :products, through: :categorizations

  validates :name, presence: true
end

class Categorization < ActiveRecord::Base
  belongs_to :product
  belongs_to :category

  validates :description, presence: true

  attr_accessor :enable # nice little thingy here
end

The form:

<%= form_for(@product) do |f| %>
  ...
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>

  <%= f.fields_for :categorizations, @product.initialized_categorizations do |builder| %>
    <% category = builder.object.category %>
    <%= builder.hidden_field :category_id %>

    <div class="field">
      <%= builder.label :enable, category.name %>
      <%= builder.check_box :enable %>
    </div>

    <div class="field">
      <%= builder.label :description %><br />
      <%= builder.text_field :description %>
    </div>
  <% end %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

And the controller:

class ProductsController < ApplicationController
  # use `before_action` instead of `before_filter` if you are using rails 5+ and above, because `before_filter` has been deprecated/removed in those versions of rails.
  before_filter :process_categorizations_attrs, only: [:create, :update]

  def process_categorizations_attrs
    params[:product][:categorizations_attributes].values.each do |cat_attr|
      cat_attr[:_destroy] = true if cat_attr[:enable] != '1'
    end
  end

  ...

  # all the rest is a standard scaffolded code

end

From the first glance it works just fine. I hope it won't break somehow.. :)

Thanks all. Special thanks to Sandip Ransing for participating in the discussion. I hope it will be useful for somebody like me.

差↓一点笑了 2025-01-10 09:20:49

使用accepts_nested_attributes_for插入中间表分类
视图表单看起来像 -

# make sure to build product categorizations at controller level if not already
class ProductsController < ApplicationController
  before_filter :build_product, :only => [:new]
  before_filter :load_product, :only => [:edit]
  before_filter :build_or_load_categorization, :only => [:new, :edit]

  def create
    @product.attributes = params[:product]
    if @product.save
      flash[:success] = I18n.t('product.create.success')
      redirect_to :action => :index
    else
      render_with_categorization(:new)
    end
  end 

  def update
    @product.attributes = params[:product]
    if @product.save
      flash[:success] = I18n.t('product.update.success')
      redirect_to :action => :index
    else
      render_with_categorization(:edit)
    end
  end

  private
  def build_product
    @product = Product.new
  end

  def load_product
    @product = Product.find_by_id(params[:id])
    @product || invalid_url
  end

  def build_or_load_categorization
    Category.where('id not in (?)', @product.categories).each do |c|
      @product.categorizations.new(:category => c)
    end
  end

  def render_with_categorization(template)
    build_or_load_categorization
    render :action => template
  end
end

内部视图

= form_for @product do |f|
  = f.fields_for :categorizations do |c|
   %label= c.object.category.name
   = c.check_box :category_id, {}, c.object.category_id, nil
   %label Description
   = c.text_field :description

use accepts_nested_attributes_for to insert into intermediate table i.e. categorizations
view form will look like -

# make sure to build product categorizations at controller level if not already
class ProductsController < ApplicationController
  before_filter :build_product, :only => [:new]
  before_filter :load_product, :only => [:edit]
  before_filter :build_or_load_categorization, :only => [:new, :edit]

  def create
    @product.attributes = params[:product]
    if @product.save
      flash[:success] = I18n.t('product.create.success')
      redirect_to :action => :index
    else
      render_with_categorization(:new)
    end
  end 

  def update
    @product.attributes = params[:product]
    if @product.save
      flash[:success] = I18n.t('product.update.success')
      redirect_to :action => :index
    else
      render_with_categorization(:edit)
    end
  end

  private
  def build_product
    @product = Product.new
  end

  def load_product
    @product = Product.find_by_id(params[:id])
    @product || invalid_url
  end

  def build_or_load_categorization
    Category.where('id not in (?)', @product.categories).each do |c|
      @product.categorizations.new(:category => c)
    end
  end

  def render_with_categorization(template)
    build_or_load_categorization
    render :action => template
  end
end

Inside view

= form_for @product do |f|
  = f.fields_for :categorizations do |c|
   %label= c.object.category.name
   = c.check_box :category_id, {}, c.object.category_id, nil
   %label Description
   = c.text_field :description
魄砕の薆 2025-01-10 09:20:49

我刚刚做了以下事情。它对我有用..

<%= f.label :category, "Category" %>
<%= f.select :category_ids, Category.order('name ASC').all.collect {|c| [c.name, c.id]}, {} %>

I just did the following. It worked for me..

<%= f.label :category, "Category" %>
<%= f.select :category_ids, Category.order('name ASC').all.collect {|c| [c.name, c.id]}, {} %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文