Every post has only one category, and i need to access category’s name by something like
p = Post.new
p.category.name = "tech"
p.save
How to do that?
class Category < ActiveRecord::Base
has_many :posts, :dependent => :destroy
attr_accessible :name, :image
end
Post.rb
class Post < ActiveRecord::Base
belongs_to :category
attr_accessible :category_id, :name, :text, :lang, :image
end
Schema.rb
create_table "categories", :force => true do |t|
t.string "name"
t.string "image"
end
Your example contains a problem.
First, you create a new post. Second, you want to assign a name to the category of the post, BUT there is no category assigned. This results in a call like
post.nil.namewherenilwould be the category object, if assigned, which isn’t the case. Sincenilhas no methodname, you get the described errorundefined method name for nil class.To solve this, you first need to assign a category to work on.
p.category = Category.firstorp.category_id = 1. After that,p.categorywill return the category object, thereforep.category.nameis valid then because it is called on a category object and not onnil.tl;dr: