Rails模型关系不起作用

时间:2013-11-14 15:24:48

标签: ruby-on-rails ruby-on-rails-4 associations has-many belongs-to

我是rails的新手,我无法让我的模型关系正常工作。我似乎无法让帖子和评论之间的关系起作用。当我调用@comments = @ post.comments时,我没有收到错误,我只是得到一个空数组。下面是一些控制台日志,我的数据库方案和我的模型。

提前感谢所有帮助。

Testing Posts
>> p = Post.first


DEPRECATION WARNING: Calling #default_scope without a block is deprecated. For example   instead of `default_scope where(color: 'red')`, please use `default_scope { where(color: 'red') }`. (Alternatively you can just redefine self.default_scope.). (called from <class:Post> at /Users/addisonhuddy/code/thatHigh/app/models/post.rb:6) 
Post Load (4.3ms)  SELECT "posts".* FROM "posts" ORDER BY created_at DESC LIMIT 1 
=> #<Post id: 517, post: "ea doloribus ut rerum repellat in nostrum dolores q...", user_id: 27, created_at: "2013-11-13 23:43:24", updated_at: "2013-11-13 23:43:24", slug: "ea-doloribus-ut-rerum-repellat-in-nostrum-dolores-q..."> 
>> p.comments 
Comment Load (3.6ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = $1  [["post_id", 517]] 
 => #<ActiveRecord::Associations::CollectionProxy []>

测试用户,帖子和评论

>> u = User.first
User Load (1.4ms)  SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1
=> #<User id: 1, email: "myemail@myemail.com", encrypted_password:
>> u.comments
Comment Load (3.5ms)  SELECT "comments".* FROM "comments" WHERE "comments"."user_id" = $1  [["user_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>
>> c = Comment.first
Comment Load (1.4ms)  SELECT "comments".* FROM "comments" ORDER BY "comments"."id" ASC LIMIT 1
=> #<Comment id: 1, comment: "dolore\net\nlaborum\nmolestias\ncum\nab\nexercitationem\nc...", post_id: nil, user_id: 2, created_at: "2013-11-13 23:43:06", updated_at: "2013-11-13 23:43:06">
>> c.user
User Load (1.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
=> #<User id: 2, email: "jazmyne_streich@gulgowski.name", encrypted_password: "$2a$10$7uBKw9GfirIKeaQleHAq7uYNpFJf9FECsDvB.vqi0um9...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2013-11-13 23:43:06", updated_at: "2013-11-13 23:43:06", username: "destinee.ritchie">>> c.post
=> nil

方案

ActiveRecord::Schema.define(version: 20131113195400) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "comments", force: true do |t|
    t.text     "comment"
    t.integer  "post_id"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "comments", ["post_id"], name: "index_comments_on_post_id", using: :btree
  add_index "comments", ["user_id"], name: "index_comments_on_user_id", using: :btree

  create_table "friendly_id_slugs", force: true do |t|
    t.string   "slug",                      null: false
    t.integer  "sluggable_id",              null: false
    t.string   "sluggable_type", limit: 50
    t.string   "scope"
    t.datetime "created_at"
  end

  add_index "friendly_id_slugs", ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true, using: :btree
  add_index "friendly_id_slugs", ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type", using: :btree
  add_index "friendly_id_slugs", ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id", using: :btree
  add_index "friendly_id_slugs", ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type", using: :btree

  create_table "posts", force: true do |t|
    t.text     "post"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "slug"
  end

  add_index "posts", ["user_id"], name: "index_posts_on_user_id", using: :btree

  create_table "users", force: true do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "username"
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree

end

用户模型

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments

  validates_presence_of :username
  validates_uniqueness_of :username, if: -> { self.username.present? }

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
end

发布模型

class Post < ActiveRecord::Base

  has_many :comments
  belongs_to :user

  default_scope order("created_at DESC")

  validates_presence_of :post

  extend FriendlyId
  friendly_id :post, use: :history

  def should_generate_new_friendly_id?
    new_record?
  end
end

评论模型

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

2 个答案:

答案 0 :(得分:0)

你得到post.comments的空数组,因为你的评论表中很可能没有post_id 517的数据

此外,您的用户模型应如下所示

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments, :through => :posts
end

用户和评论没有直接关联。有关has_many:通过关联

的更多信息,请查看documentation

答案 1 :(得分:0)

1 - 检查您的数据库关联意味着您有一列用于关联每个表中的两个表用户例如必须具有comment_id且注释必须具有User_id(如果您没有外键,则该关联赢得&# 39;工作)并检查您的迁移有时它会因任何原因而部分损坏。

2-尝试为两者之间的连接添加任何属性,例如user.comment.id,看看如果没有任何属性出现什么,那么如果一个属性出现而另一个属性没有出现则会出现连接那么这个属性命名的问题是检查数据库中的名称(区分大小写) 3-尝试重新启动服务器一次我有这个问题,它只是疯了,无缘无故重启服务器,尝试添加不同的东西,然后重做它,它可能会工作。

希望有所帮助