每个帖子只有一个类别,我需要通过类似的方式访问类别的名称
p = Post.new
p.category.name = "tech"
p.save
怎么做?
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
架构.rb
create_table "categories", :force => true do |t|
t.string "name"
t.string "image"
end