On 22 August 2013 20:56, ank k. <
li...@ruby-forum.com> wrote:
> hi!! I am a newbie in ROR.
>
> I have two models
>
> Post
> has_many :Comment
that should be
has_many :comments
note that it is plural and lower case
>
>
> Comment
> belongs_to :Post
belongs_to :post
>
>
> the error displays when I try to save a comment related to certain post.
> I get the following error
> -----------------------------------------------------------------
> undefined method `comment' for nil:NilClass
> -----------------------------------------------------------------
> my comment controllers
>
> def new
> @comment = Comment.new
> render :layout => false
> end
>
> def create
> @post = Post.find_by_id(params[:id])
> @post_comment = @post.comment.create(params[:comment])
You have not told us which line the error points to but I guess it is
the one above. If so then it is saying that @post is nil, so your
find_by_id did not find anything. You don't need to use find_by_id,
you can just use
@post = Post.find( params[:id] )
Perhaps there is not a Post object with the correct id. If you look
in log/development.log you will see the params you are passing which
may give you a clue.
I suggest, however, that as a beginner you work right through a good
tutorial such as
railstutorial.org (which is free to use online).
That will show you the basics of rails.
Also see the Rails Guides.
Colin