仅删除Rails 4中表之间的连接记录

时间:2017-08-20 19:16:20

标签: mysql ruby-on-rails ruby ruby-on-rails-4 has-and-belongs-to-many

我有3个Rails模型:

class User < ActiveRecord::Base
  has_and_belongs_to_many :char_factors
end

class CharFactor < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class UserCharFact < ActiveRecord::Base
  belongs_to :user
  belongs_to :char_factor
end

上述UserCharFactor模型通过UserCharFact模型加入。

我创造了新的关系:

def create
  @user_character = UserCharFact.create({:user_id => @user.id, :char_factor_id => factor_id.id})
end

以上情况似乎正常。但我找不到删除两个表之间的特定join relation的方法。我尝试了以下方法:

def destroy
  @user_character = CharFactor.find(params[:id])
  @user.char_factors.delete(@user_character)
end

但它实际上删除了CharFactor表中的值而不是删除关联

2 个答案:

答案 0 :(得分:1)

删除它就像删除任何其他模型记录一样。

user_char_factor = UserCharFactor.find_by(user_id: user_id, char_factor_id: char_factor_id)
user_char_factor.destroy if user_char_factor

答案 1 :(得分:1)

UserCharFact.where(char_factor_id: params[:id], user_id: @user.id).destroy_all