NoMethodError(未定义的方法`posts'为nil:NilClass)

时间:2015-04-03 14:33:43

标签: ruby-on-rails ruby-on-rails-4 heroku nomethoderror griddler

我对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日志时收到标题中的错误。

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

User.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

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

1 个答案:

答案 0 :(得分: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