Witam,
Problem jest nastepujacy w momencie gdy chce stworzyc nowy post i nie wpisze tytulu wywala blad
[code]NoMethodError in Posts#create
Showing /home/nikos/Documents/sites/blog2/app/views/posts/_form.html.erb where line #17 raised:
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.collect
Extracted source (around line #17):
14:
15:
16: <%= f.label(:category_id, “Category”) %>
17: <%= f.select(:category_id, @categories.collect {|s| [s.name, s.id]}) %>
18: <%= link_to(“Create Category”, {:controller => ‘categories’, :action => ‘new’}, :class => ‘back-link’) %>
19:
20:
Gdy wpisze tytul a potem podczas edit go skasuje wyswietla komunikat ze tytul nie moze byc pusty.
Oto modele Post
class Post < ActiveRecord::Base
belongs_to :category
validates :title, :presence => true
end
Category
class Category < ActiveRecord::Base
has_many :posts
validates :title, :presence => true
end
Oraz post_controller
[code]class PostsController < ApplicationController
layout ‘public’
before_filter :confirm_logged_in, :except => [:show, :index]
GET /posts
GET /posts.json
def admin
render(‘admin’)
end
def index
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @posts }
end
end
GET /posts/1
GET /posts/1.json
def show
@post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => @post }
end
end
GET /posts/new
GET /posts/new.json
def new
@post = Post.new
@categories = Category.all
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @post }
end
end
GET /posts/1/edit
def edit
@post = Post.find(params[:id])
@categories = Category.all
end
POST /posts
POST /posts.json
def create
@post = Post.new(params[:post])
respond_to do |format|
if @post.save
format.html { redirect_to @post, :notice => ‘Post was successfully created.’ }
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
PUT /posts/1
PUT /posts/1.json
def update
@post = Post.find(params[:id])
@categories = Category.all
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
DELETE /posts/1
DELETE /posts/1.json
def destroy
@post = Post.find(params[:id])
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :ok }
end
end
end[/code]
W tabeli post dodany jest category_id Jesli ktos moze prosze o sprawdzenie
RoR 3.1.0