【问题标题】:How to use Rails detect in Rails on incoming Params如何在 Rails 中使用 Rails 检测传入的参数
【发布时间】:2014-11-20 15:25:21
【问题描述】:

所以最近我被帮助找到了一种在 rails 中使用 detect 从文本中获取 url 的方法……但是如果可能的话,这对我来说在控制器中也非常有用。

我的控制器抓取了一些信息并根据传入的参数在数据库中创建了一个新条目,看起来像这样;

    @received_msg = Message.create(:content => params[:Text], :user_id => user.id, :status => 'new') 

现在,我希望在创建操作的控制器中使用 detect,我可以在 :content 中搜索特定的文本或符号,并允许我的用户在内容中定义一些东西,但我会将其分配给不同的列。我确定这不是很清楚,所以让我举例说明。

示例:

假设我的用户发送的消息内容如下;

   "Hey there, you should check this type of website out and make sure that its good to go" 

现在,我为提交此邮件的用户分配了一个 USER_ID,但在用户提交邮件之前,原始所有者可能是其他人。所以我想我会允许我的 user_id 在他们的消息中输入@John,这意味着消息的原始所有者是JOHN.. 新消息看起来像这样;

   "Hey there, you should check this type of website out and make sure that its good to go @John"

现在在我的控制器中,当该消息被创建为记录时,我想将JOHN 分配给username 列;我认为这样的事情会起作用,但它给了我错误.detect undefined..

   @received_msg = Message.create(:content => params[:Text], :user_id => user.id, :status => 'new', :username => (params[:Text].detect {|original_sender| original_sender.start_with? "@"))

可能括号太多了?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你最后缺少}

    @received_msg = Message.create(:content => params[:Text], :user_id => user.id, :status => 'new', :username => (params[:Text].detect {|original_sender| original_sender.start_with? "@"}))
    

    你也可以用下面的来做你想要的

    @received_msg = Message.create(:content => params[:Text], :user_id => user.id, :status => 'new', :username => params[:Text].split.find{|w| w.start_with?("@")})
    

    【讨论】:

    • 只返回undefined method split' for nil:NilClass`
    • 您确定您访问的参数正确吗?是params[:Text] 还是params[:text]
    • 肯定是params[:Text]...没有.split.find 也能正常工作
    • 是的。因为如果您从params 访问任何不存在的符号,它将返回nileg: params[:random] => nil
    • 但它确实存在... :) 因为我将它用于:content => params[:Text],它确实获取消息文本并将其放入:content
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2018-12-01
    • 2011-08-03
    • 1970-01-01
    相关资源
    最近更新 更多