gpt4 book ai didi

ruby-on-rails - 删除组中的单个用户 - Active Record

转载 作者:数据小太阳 更新时间:2023-10-29 07:42:24 24 4
gpt4 key购买 nike

我有两个模型 GroupPerson。两者都是 HABTM,但我希望一个人能够在不删除该组的情况下退出特定组,只是该组中的人。我一直在尝试在控制台中解决这个问题,但我似乎无法理解。我将显示我的代码以进行澄清。

我目前正在做这个方法

def delete_from_group(phone_number)
person = Person.find_by(phone_number: phone_number)
person.groups.destroy
end

这是我的 Controller 。

def create
# Grab the phone number from incoming Twilio params
@phone_number = params[:From]
# Find the subscriber associated with this number or create a new one
@subscriber = Person.find_or_create_by(phone_number: @phone_number)
@delete_group = Person.find_by(phone_number: @phone_number)

# Update location data
@subscriber.update(
city: params[:FromCity],
state: params[:FromState],
zip: params[:FromZip],
country: params[:FromCountry]
)

@body = params[:Body].to_s.downcase.strip
begin
# Process the command from our Subscriber
output = process_message(@body, @subscriber, @delete_group)
rescue
output = "Something went wrong. Try again."
end

# Render the TwiML response

respond(output)
end

private

def process_message(message, subscriber, delete_group)
if worker_groups.include?(message)
subscriber.update(subscribed: true)
subscriber.add_to_group(message)
"You have been subscribed to the #{message.capitalize} list"

elsif message == "stop volunteer"
delete_group.delete_from_group("volunteer")
"You have been unsubscribed from the specified list"
elsif message == "stop dancer"
delete_group.delete_from_group("dancer")
"You have been unsubscribed from dancer list"
elsif message == "stop staff"
delete_group.delete_from_group("staff")
"you have been unsubscribed from staff list"

elsif message == "tulip" || message == "stem"
subscriber.update(subscribed: message == "tulip")
subscriber.add_to_group("visitor")

if subscriber.subscribed
"You are now subscribed for updates."
else
"You have unsubscribed from notifications. Text 'TULIP' to start receieving updates again."
end
else
"Sorry, we don't recognize that command. Available commands are: 'TULIP' or 'STEM'."
end
end

def worker_groups
%w(dancer staff volunteer)
end

def worker_groups
%w(dancer staff volunteer)
end

最佳答案

如果您有要删除的组 ID 作为变量 group_id:

 person = Person.find_by(phone_number: phone_number)
group = person.groups.find(group_id)

if group
person.groups.delete(group)
end

参见 this awesome post on the subject

另见 Rails documentation :

collection.delete(object, …) Removes one or more objects from the collection by removing their associations from the join table. This does not destroy the objects.

关于ruby-on-rails - 删除组中的单个用户 - Active Record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36336528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com