0

我希望我的 Rails 应用程序能够接收传入的电子邮件并以特定方式解析它们。

传入控制器.rb

class IncomingController < ApplicationController
  skip_before_action :verify_authenticity_token, only: [:create]
  skip_before_action :authenticate_user!, only: [:create]
  def create
    # Find the user
     user = User.find_by(email: params[:sender])

     # Find the topic
     topic = Topic.find_by(title: params[:subject])

     # Assign the url to a variable after retreiving it from
     url = params["body-plain"]

     # If the user is nil, create and save a new user
     if user.nil?
       user = User.new(email: params[:sender], password: "password")
       user.save!
     end

     # If the topic is nil, create and save a new topic
      if topic.nil?
        topic = Topic.new(title: params[:subject], user: user)

        topic.save!
      end

      bookmark = topic.bookmarks.build(user: user, url: url, description: "bookmark for #{url}")

      bookmark.save!

    # Assuming all went well.
    head 200
  end
end

使用这个控制器,我只能提取 3 个值 = 用户:发件人、主题:主题和 url “body-plain”。

如何在电子邮件中添加第四个值来解析:description?

4

1 回答 1

1

理论上,params[:description]实现应该与params方法中使用的其他项相同,您只需要确保调用您的IncomingController#create操作的任何内容都发送:description参数。

或者,如果您无法将参数添加到调用控制器操作的任何内容,也许您可​​以将其添加到params['body-plain']您当前用于url? 您可以使用序列化文本格式在电子邮件正文中存储多个字段,例如(使用 YAML):

url: http://example.com
description: I'm a description

然后在您的控制器中,您将像这样解析该字段:

class IncomingController < ApplicationController
  require 'yaml'
  def create
    # ...
    body_params = YAML.load(params['body-plain'])
    url = body_params[:url]
    description = body_params[:description]
    # ...
  end
end
于 2016-08-11T23:32:58.043 回答