仅删除 Rails 4 中表之间的连接记录
Delete only join record between tables in Rails 4
我有 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
以上似乎工作正常。但是我找不到在 2 table 秒之间删除特定 join relation
的方法。我尝试了以下方法:
def destroy
@user_character = CharFactor.find(params[:id])
@user.char_factors.delete(@user_character)
end
但它实际上是从 CharFactor
table 中删除值,而不是仅仅删除关联
就像删除任何其他模型记录一样删除它。
user_char_factor = UserCharFactor.find_by(user_id: user_id, char_factor_id: char_factor_id)
user_char_factor.destroy if user_char_factor
UserCharFact.where(char_factor_id: params[:id], user_id: @user.id).destroy_all
我有 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
以上似乎工作正常。但是我找不到在 2 table 秒之间删除特定 join relation
的方法。我尝试了以下方法:
def destroy
@user_character = CharFactor.find(params[:id])
@user.char_factors.delete(@user_character)
end
但它实际上是从 CharFactor
table 中删除值,而不是仅仅删除关联
就像删除任何其他模型记录一样删除它。
user_char_factor = UserCharFactor.find_by(user_id: user_id, char_factor_id: char_factor_id)
user_char_factor.destroy if user_char_factor
UserCharFact.where(char_factor_id: params[:id], user_id: @user.id).destroy_all