我试图编写代码,让我搜索通过表单提交的内容,并在内容中找到电子邮件地址。下面是代码,以及我收到的错误消息。
Error: undefined method `match' for {"content"=>"this is a test testemail@gmail.com"}:ActionController::Parameters
代码:
class ChallengesController < ApplicationController
def create
@challenge = current_user.challenges.build(challenge_params)
challenge_params.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
# ...
end
private
def challenge_params
params.require(:challenge).permit(:content)
end
end
答案 0 :(得分:1)
您正在哈希上应用match
。
challenge_params
是一个哈希。根据错误消息,此哈希包含一个键content
,您希望将其用于match
,从而将match
行重写为:
challenge_params["content"].match(/\b[A-Z0-9\._%+-]+@[A-Z0-9\.-]+\.[A-Z]{2,4}\b/i)
答案 1 :(得分:0)
我是红宝石的新手,所以我的回答可能非常“非常好”,但有时最简单的想法是最好的...... 我这样做的方法是搜索@符号的索引。然后分析符号前后的每个字符,直到找到空格并保存这些索引号。使用这些索引号从字符串中提取电子邮件地址。
def email_address(str)
at_index = str.index('@')
temp = (at_index - 1)
while str[temp] != ' '
temp -= 1
end
begining_index = (temp + 1)
temp = (at_index + 1)
while str[temp] != ' '
temp += 1
end
end_index = temp
return str[begining_index..end_index]
端