2012-04-23 8 views
1

3プロジェクトのRailsにはnilのIDと呼ばれる:私はこの問題を解決するにはどうすればよいランタイムエラー - 私は私のフォームを送信しようとすると、私は(/ POSTS/SHOWを)このエラーを取得してい

RuntimeError in Posts#show 

Showing /Users/fkhalid2008/loand/app/views/posts/show.html.erb where line #1 raised: 

Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id 
Extracted source (around line #1): 

1: <%= form_remote_tag (:update => 'message', :url => {:controller => 'main', :action => 'send_message', :user_id => @post.user.id}) do %> 
2: <br> 
3: <br /> 
4: <br /> 

関連するコードは以下の通りです:

/閲覧/ POSTS/SHOW

<%= form_remote_tag (:update => 'message', :url => {:controller => 'main', :action => 'send_message', :user_id => @post.user.id}) do %> 
<br> 
<br /> 
<br /> 
<div class="field"> 

こんにちは!私の名前は<%= f.text_field:subject%>です。私はあなたの広告に応じてあなたに連絡しています。私はもっ​​と学ぶことに興味があるので連絡してください!ここに私の連絡先の詳細があります:<%= f.text_field:body%>。 提出 <%エンド%>

Postモデル

class Post < ActiveRecord::Base 

belongs_to :user 

attr_accessible :title, :job, :location, :salary 

validates :title, :job, :location, :salary, :presence => true 
validates :salary, :numericality => {:greater_than_or_equal_to => 1} 

default_scope :order => 'posts.created_at DESC' 
end 

ユーザ・モデル

class User < ActiveRecord::Base 

has_many :posts 
has_one :profile 
has_private_messages 

attr_accessible :email 

validates_presence_of :email 
validates_uniqueness_of :email, :message =>"Hmm, that email's already taken" 
validates_format_of :email, :with => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i, :message => "Hi! Please use a valid email" 


end 

ポストCONTROLLER

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

respond_to do |format| 
    format.html # show.html.erb 
    format.json { render :json => @post } 
end 
end 

def new 
@post = Post.new 
@post.user = current_user 

respond_to do |format| 
    format.html # new.html.erb 
    format.json { render :json => @post } 
end 
end 

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

def create 
    @post = Post.new(params[:post]) 
    @post.user = current_user 

    respond_to do |format| 
     if verify_recaptcha && @post.save 
      format.html { redirect_to :action=> "index"} 
      format.json { render :json => @post, :status => :created, :location => @post } 
     else 
      format.html { render :action => "new" } 
      format.json { render :json => @post.errors, :status => :unprocessable_entity } 
     end 
    end 
end 

def update 
@post = Post.find(params[:id]) 
@post.user = current_user 

respond_to do |format| 
    if @post.update_attributes(params[:post]) 
    format.html { redirect_to @post, :notice => 'Post was successfully updated.' } 
    format.json { head :ok } 
    else 
    format.html { render :action => "edit" } 
    format.json { render :json => @post.errors, :status => :unprocessable_entity } 
    end 
end 
end 

APPLICATIONコントローラは

class ApplicationController < ActionController::Base 
protect_from_forgery 

private 

def current_user 
    @_current_user ||= session[:current_user_id] && 
    User.find_by_id(session[:current_user_id]) 
end 

end 

メインコントローラ(SEND_MESSAGEがここで定義される)

class MainController < ApplicationController 

def send_message 
message = Message.new 
message.subject = params[:subject] 
message.body = params[:message] 
message.sender = User.find session[:user] 
message.recipient = User.find params[:user_id] 
if message.save 
    ContactMailer.deliver_message_email message.recipient.email, message.id, request.host 
    return redirect_to "/posts" 
else 
    render :text => "Hmm. Something seems to be wrong...let me look into it" 
end 
end 
+0

あなたの投稿のコントローラのshowアクションで@postを定義しましたか? – DanS

+0

いいえ(上記のコントローラを参照)。これを修正するには何を追加する必要がありますか? – hikmatyar

+0

ありがとうございます( '@post = Post.find(params [:id])') – DanS

答えて

1

@postインスタンス変数で表されるポストレコードにユーザーが割り当てられていません。

投稿をするにはログインする必要がありますか? おそらくあなたはどこかに現在のユーザを定義していますか?

このフォームを使用して、コントローラのアクション

は、ポストレコードにユーザーを割り当てる必要が

def new 
    @post = Post.new 
    @post.user = current_user # You will need to get the current user from somewhere 
    respond_to do |format| 
    format.html # new.html.erb 
    format.json { render :json => @post } 
    end 
end 

UPDATE

現在のユーザーは、あなたが確認するためにチェックを追加する必要が割り当てられていることを確認するために、ユーザーはコントローラのアクションでログインします。これは通常、前のフィルタを追加して現在のユーザを認証し、現在のユーザがログアウトした場合にログインページにリダイレクトすることによって行われます。 はこれを見ては、中およびログアウトを説明するためにキャストレールがあり、フィルタ前http://railscasts.com/episodes/250-authentication-from-scratch

にリダイレクトここでは、キャストの改訂版がありますが、あなたはその http://railscasts.com/episodes/250-authentication-from-scratch-revised

も価値のサブスクリプションが必要になりますCRすなわち - IMO

のアップデート

エンドを払ってあなたは/また、ポストレコードを更新どんなアクションで、現在のユーザーを割り当てる必要がありますする必要があります正確に同じ方法でアクションを実行し、更新します。あなたがポストレコードに割り当てられたユーザーを持っていないので、

はまた、あなたはあなたがあなたに@ post.userを使用することができます500エラー

を取得しないように、フォームでこのシナリオを処理する必要があります。ブランク?あなたにこれを手伝ってくれるブールチェック

<% if @post.user.blank? %> 
    <h2>There is no user assigned to this post record! This should never happen ad you should never see this message, please contact support if etc... </h2> 
<% else %> 
<!-- Place all your current form code here --> 
<% end %> 
+0

私はあなたが言ったすべてを行いました(ブールチェックを除いて) post.userと同じエラー/ 'nil'!私は何を間違っているのですか?更新されたコードは上に添付されています – hikmatyar

+0

ブールチェックを追加する必要があります。割り当てているcurrent_userが何も設定されていないため、エラーが発生しています。私は答えを更新する – jamesc

+0

ありがとう - ちょうどあなたが投稿したレールキャストの詳細を見た、私はこれがユーザーがログインしている認証システムのためだと思う。しかし、これは私が望むものではありません。私が欲しいのは、これの行に沿ったものです。https://jobpoacher.com/blog/blog/2012/02/13/what-c​​raigslist-did-right-user-management-without-passwords/すなわち、パスワードまたはユーザ名なしのユーザ認証である。リンクに記載されているものを複製しようとすると、それが動作するかどうかを見てみましょう! – hikmatyar

1

@post.userがあるので、あなたがエラーを取得している(これは私がCURRENT_USERを定義しています場所です) nil:user_id => @post.user.idに設定します。

ポストコントローラのshowアクションに@postを定義し、有効なユーザ関連があることを確認してください。

+0

私は@ postをどのように定義すべきですか? (レールに新しくありません)。 – hikmatyar

+1

'@post = Post.find(params [:id])'は通常OKです。コンソールで少しのテストを行います: 'post = Post.find(id)'& 'post.user' – DanS

+0

これらのいずれかが' nil'を返す場合は問題があります... – DanS

関連する問題