如何以正确的方式保存Rails上的HABTM关系

lka*_*ono 5 ruby-on-rails has-and-belongs-to-many

我实际上需要一些来自高级Ruby/Rails开发人员的建议,了解保存has_and_belongs_to_many关联的常用和正确方法是什么?

这是我做的,但对我来说它感觉非常脏,我真的不喜欢在我的应用程序中看到该代码:)

车型/ company.rb

class Company < ActiveRecord::Base
  has_and_belongs_to_many :type_taxes

  ## Add Type taxes association
  def insert_types_taxes( types_taxes )
    self.type_taxes.clear
    self.type_taxes << types_taxes
  end
end
Run Code Online (Sandbox Code Playgroud)

车型/ taxe.rb

class Taxes < ActiveRecord::Base
  has_and_belongs_to_many :societes
end
Run Code Online (Sandbox Code Playgroud)

控制器/ societes_controller

class SocietesController < ApplicationController
  # I use basically the same code for the update method
  def create
    params[:societe][:type_taxes_ids] ||= []
    @societe = Societe.new( societe_params )
    @societe.user_id = current_user.id
    if @societe.save
      add_types_taxes_to_societe
      redirect_to societes_path
    else
      load_resources
      render :new
    end
  end

  private
    def add_types_taxes_to_societe
      types_taxes = TypeTaxe.find params[:societe][:type_taxe_ids]
      @societe.insert_types_taxes types_taxes
    end
end
Run Code Online (Sandbox Code Playgroud)

当这个工作正常时,它对我来说真的很脏.它也没有告诉我创建的关联是成功还是成功.

任何建议都非常欢迎提高我的技能和我的代码:)

谢谢

dav*_*lis 9

当您使用=直接重新分配HABTM关联时,它将删除您分配给它的内容中不存在的联接记录.也就是说:

types_taxes = TypeTaxe.find params[:societe][:type_taxe_ids]
@societe.types_taxes = types_taxes
Run Code Online (Sandbox Code Playgroud)

与你所拥有的基本相同.它只会根据需要删除和添加记录,因此如果重叠,重叠记录将保持分配状态.