0

我对 Rails 非常陌生,并且正在使用 gem griddler 来解析一些传入的电子邮件。我使用了 github 站点上的所有代码,它在这里提供了一个示例 emailprocessor.rb:

class EmailProcessor
  def initialize(email)
    @email = email
  end

  def process
    //re-done with help from @Kris
    user = User.find_or_create_by(email: @email.from[:email]) do |u|
      u.email = @email.from[:email]
      u.name = @email.from[:name]
    end    


    user.posts.create!(
      subject: @email.subject,
      body: @email.body,

      attachment: @email.attachments,
      from: @email.from[:email]
    )
  end
end

我知道我需要以某种方式和某处声明帖子,但我在这里和 rails 网站上环顾四周,并没有找到任何可以帮助我创建它的东西。当电子邮件服务器尝试发布到页面时,运行 heroku logs -t 时出现标题错误。

这是我可能需要的其余文件以及我尝试过的文件:

用户.rb:

class User < ActiveRecord::Base
    has_many :posts
end

Post.rb:

class Post < ActiveRecord::Base
    belongs_to :user
end

create_posts.rb

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
      t.string :subject
      t.string :body
      t.string :from
      t.string :attachment

      t.timestamps
    end
  end
end

users_controller.rb

class UserController < ApplicationController
  def list
    @users = User.find(:all)
  end

  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def edit
  end

  def create
    @user = User.new(params[:user])
    if @user.save
        redirect_to :action => 'list'
    else
        render :action => 'new'
    end
  end
end

post_controller.rb

class PostController < ApplicationController


 def list
    @posts = Post.find(:all)
  end

  def index
    @posts = Post.all
  end

  def show
    @post = Post.find(params[:id])
  end

  def new
    @post = Post.new
  end

  def edit
  end

  def create
    @post = Post.new(params[:post])
    if @post.save
        redirect_to :action => 'list'
    else
        @post = Subject.find(:all)
        render :action => 'new'
    end
  end

end

非常感谢任何帮助,我想知道我做错了什么,以便将来避免它

4

1 回答 1

1

在数据库中找不到电子邮件地址,因此user为零。您可以使用以下代码即时创建用户:

def process
  user = User.find_or_create_by(email: @email.from[:email]) do |u|
    # todo: set some other properties on the new user u, e.g. the name
  end

  user.posts.create!(
    subject: @email.subject,
    body: @email.body,      
    attachment: @email.attachments,
    from: @email.from[:email]
  )
end

另见ActiveRecord::Relation::find_or_create_by

于 2015-04-03T15:09:54.587 回答