【问题标题】:Rails: How to set up Active Record Associations?Rails:如何设置 Active Record 关联?
【发布时间】: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


【解决方案1】:

您应该确保在创建帖子表的迁移中包含用户 ID。 在您的迁移文件中(在 db/migrate 文件夹中,您会找到一个名为 20130325105934_create_posts.rb 的文件)

在文件中,您将找到迁移代码。沿着其他声明的属性添加

class CreatePosts < ActiveRecord::Migration
  def change
    create_table :posts do |t|
     ...... 
     t.integer :user_id
     ......
  end

结束

应该足以让事情顺利进行:-)

在您的代码中,您可以创建一个新用户

@user = User.new(:login => "my_user", .....)

然后使用这两种方式之一添加帖子(还有其他两种方式)。

post = Post.new(:title => "something", :text => "more of something", :user_id = @user.id)

   post = Post.new(:title => "something", :text => "more of something")
   @user.posts << post

【讨论】:

  • 您好,感谢您的快速回复。我现在已经全部设置好了,但是如果我做一个@user.posts.any? 我会得到错误,即使@user 是我已经发布了一些帖子的用户。知道为什么吗?
  • 奇怪,我做了一个玩具项目,运行控制台并为我工作。您使用的是哪个版本的导轨?
  • 我添加了一些代码,您可以将其用作指南。无效请留言
  • 我正在使用Rails 3.2.13。我在控制台中尝试了最后一段代码(post = Post.new():title....@user.posts &lt;&lt; post),它成功了!但我不知道如何在我的代码中测试它?我做了add_user_id_to_posts user_id:integer,做了迁移并将t.integer :user_id 添加到数据库迁移文件中。有什么我错过的吗?
  • 通常它会变得凌乱。当我想添加一列时(当然有可能),我将在创建表的迁移中添加 declamation。如果您将数据保存在某处,只需执行 rake db:reset 即可重新创建数据库。你能试试吗?
猜你喜欢
  • 1970-01-01
  • 2017-10-14
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多