【发布时间】:2013-03-25 09:53:54
【问题描述】:
我对 Rails 比较陌生,做最简单的事情:关联用户和帖子。我读了this,但我还需要做些什么才能让它工作(或者这是唯一的事情)?:
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
【问题讨论】:
-
对我来说看起来不错。只要
users表有post_id列。你有任何错误吗? -
这应该可以,您应该能够调用
@user.posts来获取给定用户的所有帖子,或者调用@post.user 来获取给定帖子的用户。你有什么错误吗?! -
我没有收到任何错误,但如果我执行@user.posts,我会得到
[],即使我已经发布了一些帖子。但是users表会有post_id吗?不是只有posts表会有user_id吗?
标签: ruby-on-rails activerecord associations