我有一个控制器方法名称process_message
,其目的是根据收到的消息将人员签名到特定的组。现在一切正常,除非它会一遍又一遍地向一个人报名。我正在尝试添加一些快速代码,以便它们只能注册一次特定的组。我认为我想出来但是当我尝试执行我所写的内容时,我收到了错误。为了清楚起见,我会显示一些截图和一些代码。
这是我的控制器方法
def process_message
if message_params[:action] == 'subscribe'
# result = SubscribeToGroup.call(message_params)
# results.success? ? result.message : result.error
message_params[:id] = "visitor" if message_params[:id] == "tulip" # hack for now
@group = Group.find_by(name: message_params[:id])
if @group && @subscriber.groups << @group unless groups.include? (@group) ^
@group.response
else
'You cannot subscribe to unknown group'
end
elsif message_params[:action] == 'stop'
# result = UnsubscribeToGroup.call(message_params)
# results.success? ? result.message : result.error
group_name = message_params[:id]
@group = @subscriber.groups.find_by(name: group_name)
@subscriber.groups.destroy(@group) if @group
"You are now unsubscribed from #{group_name.upcase} notifications. Text '#{group_name.upcase}' to start receieving updates again."
else
"Sorry, we don't recognize that command."
end
rescue Exception => e
"Something went wrong. Try again. #{e.message}"
end
你可以在第7行看到我在那里有一些代码,我认为会保留消息来注册一个人两次,但它不起作用,这是我运行Rspec时的错误消息。
我希望我的问题很明确,如果您需要更多代码,请告诉我。
答案 0 :(得分:3)
我避免将if
和unless
放在同一行
这是你想要做的吗?
# You may have meant to provide `@subscriber.groups` instead of `groups` here. I'm not sure from information provided.
unless groups.include?(@group)
@subscriber.groups << @group
end
if @group && @subscriber.groups.present?
# ...
答案 1 :(得分:2)
您在一行中有if
和unless
。这会给你语法错误。
这里的逻辑并不清楚。 也许你想要的只是通过添加一个换行来完成,所以除非语句在if-block内,而不是if-condition。
if @group.present?
@subscriber.groups << @group unless groups.include? (@group)
@group.response
else
'You cannot subscribe to unknown group'
end