我对 Rails 比较陌生,做最简单的事情:关联用户和帖子。我读了这个,但是我还需要做些什么才能让它工作(或者这是唯一的事情)?:
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end
class Post < ActiveRecord::Base
belongs_to :user
end
更新:
我不能让它工作。当我与登录用户一起发帖时,我@user.posts.any?
在控制台中发帖时会出错。我的代码:
post.rb
class Post < ActiveRecord::Base
attr_accessible :title, :user_id
belongs_to :user
before_create :default_values
user.rb(我使用设计)
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :posts, dependent: :destroy
end
20130320162700_create_posts.rb
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.integer :user_id
t.timestamps
end
end
end