所以我有两个模型 - Status
和Post
。
状态可以是:Empty
,Half
或Full
。
每个post
一次只能有1个状态,即帖子只能是empty
或half
等。它必须是其中之一。< / p>
但是,状态可以有很多帖子。因此,Empty
状态可能有20个帖子。
从协会的角度来看,最好的方法是什么?
我最初认为Post
has_one Status
。但问题是,Status
必须belong_to
一个Post
。
所以现在,我把它作为:
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)
没有将正确的Status对象分配给当前帖子。
答案 0 :(得分: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?