我有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
上述User
和CharFactor
模型通过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
表中的值而不是删除关联
答案 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