【问题标题】:Correct association for a status of another model正确关联另一个模型的状态
【发布时间】:2014-08-30 13:55:30
【问题描述】:

所以我有两个模型 - StatusPost

状态可以是:EmptyHalfFull

每个post在任何时候只能有1个状态,即帖子只能是emptyhalf等。它必须是3个之一。

但是,一个状态可以有多个帖子。所以Empty 状态可能有 20 个帖子。

从关联的角度来看,解决此问题的最佳方法是什么?

我最初认为Post has_one Status。但问题在于,Status 必须是 belong_toPost

所以现在,我有它:

Status   has_many :posts
Post   belongs_to :status, counter_cache: true

但是每当我想为帖子分配状态时,我都必须倒退,感觉很奇怪。

即我必须这样做:

> g = Post.second
  Post Load (0.7ms)  SELECT  "posts".* FROM "posts"   ORDER BY "posts"."id" ASC LIMIT 1 OFFSET 1
 => #<Post id: 19, title: "10PP gives you 1 on 1", photo: "1-on-1-Icon.jpg", body: "10PP gives you the real one on one attention you c...", created_at: "2014-08-30 10:48:18", updated_at: "2014-08-30 10:48:18", user_id: 1, ancestry: nil, file: nil, status_id: nil> 
2.1.1p76 :010 > half = Status.second
  Status Load (0.5ms)  SELECT  "statuses".* FROM "statuses"   ORDER BY "statuses"."id" ASC LIMIT 1 OFFSET 1
 => #<Status id: 2, name: "half", created_at: "2014-08-28 08:04:42", updated_at: "2014-08-28 08:04:42", posts_count: nil> 
2.1.1p76 :011 > half.posts << g
   (0.1ms)  BEGIN
  SQL (0.3ms)  UPDATE "posts" SET "status_id" = $1, "updated_at" = $2 WHERE "posts"."id" = 19  [["status_id", 2], ["updated_at", "2014-08-30 11:37:16.121245"]]
  SQL (0.4ms)  UPDATE "statuses" SET "posts_count" = COALESCE("posts_count", 0) + 1 WHERE "statuses"."id" = 2
   (0.9ms)  COMMIT
  Post Load (0.8ms)  SELECT "posts".* FROM "posts"  WHERE "posts"."status_id" = $1  [["status_id", 2]]
 => #<ActiveRecord::Associations::CollectionProxy [#<Post id: 19, title: "10PP gives you 1 on 1", photo: "1-on-1-Icon.jpg", body: "10PP gives you the real one on one attention you c...", created_at: "2014-08-30 10:48:18", updated_at: "2014-08-30 11:37:16", user_id: 1, ancestry: nil, file: nil, status_id: 2>]> 

我宁愿采用另一种方式,即为帖子分配状态。

我觉得这不是最好的方法,但不知道如何解决它。

另外,我将如何处理PostsController#Create

现在,我刚刚:

@post = current_user.posts.new(post_params)

这不会将正确的状态对象分配给当前帖子。

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-4 associations


    【解决方案1】:

    您可以尝试其他方式使用 enum http://edgeguides.rubyonrails.org/4_1_release_notes.html#active-record-enums

    class Post < ActiveRecord::Base
      enum status: [ :empty, :half, :full ]
    end
    
    Post.full
    Post.first.empty?
    

    【讨论】:

    • 当然是,因为在同一条记录中,没有关系,只有一个status字段(甚至不是string只是int)
    • 出于好奇,我怎样才能知道有多少帖子的状态为:half
    • 最简单的方法可能是Post.half.size 或类似:Post.where(status: Post.statuses[:half])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多