我對rails非常陌生,並且正在使用gem griddler來希望解析一些傳入的電子郵件。我用所有的代碼從GitHub的網站,它提供了一個示例emailprocessor.rb這裏:NoMethodError(未定義的方法'posts'爲nil:NilClass)
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
我知道我需要以某種方式和地方申報的職位,但我已經在這裏和在軌道站點附近看並沒有找到任何東西來幫助我創建它。運行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_con troller.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
任何幫助非常感謝,我想知道我在做什麼錯了,所以我能避免它在未來
錯誤表明'用戶'是零,這反過來表明數據庫中沒有用戶給定的電子郵件地址。當用戶不存在時你想要發生什麼? – Kris 2015-04-03 14:40:57
哦,哎呀,我覺得愚蠢......我一直在看帖子這整個時間,但現在你說,這使得完全有道理......如果用戶不存在,我想用該電子郵件創建一個新用戶,如何我會這樣做嗎? @Kris – seanscal 2015-04-03 14:43:24