I have 3 Rails models as:
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
In the above User
and CharFactor
models are joined through the UserCharFact
model.
I'm creating new relations as:
def create
@user_character = UserCharFact.create({:user_id => @user.id, :char_factor_id => factor_id.id})
end
And the above seems to be working properly. But I can't find a way to delete a specific join relation
between 2 tables. I tried the following:
def destroy
@user_character = CharFactor.find(params[:id])
@user.char_factors.delete(@user_character)
end
But it actually deletes the value from CharFactor
table rather than just deleting the association
You delete it just like you delete any other model records.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.