0

我是 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
4

2 回答 2

0

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

您的用户模型也应如下所示

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

用户和评论没有直接关联。查看文档以获取有关 has_many 的更多信息:通过关联

于 2013-11-14T15:41:52.277 回答
0

1-检查您的数据库关联,这意味着您有一个用于关联每个表中的两个表用户的列,例如用户必须有一个comment_id,评论必须有一个User_id(如果您没有外键,则关联将不起作用)并执行有时检查您的迁移,无论出于何种原因,它都会部分损坏。

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

希望有帮助

于 2016-07-18T18:44:42.653 回答