AnA*_*ice 1 activerecord ruby-on-rails activemodel ruby-on-rails-3
我需要一些帮助构建一个表,然后从Rails 3中获取该表中的数据.
这是分解:
模型 - 这里涉及的3个模型是:
活动表:
id | thread_id | participants
Run Code Online (Sandbox Code Playgroud)
示例记录看起来像:
1 | 300 | 3,1,5,67,13
2 | 333 | 3,12
3 | 433 | 1,12
4 | 553 | 1,12, 67
Run Code Online (Sandbox Code Playgroud)
如果参与者是user_ids列表,如果有更好的方法来存储user_ids,请告诉我.我还没有建造它.
填充活动表后.然后,我希望能够按以下方式进行查询:选择参与者字段中包含67的participant_id的所有活动记录.
我希望以上内容清楚,如果不是,请告诉我.想法?思考?建议.
谢谢
虽然在列中存储多个值很有吸引力,但最终会有人受伤.你最好建立一个连接表来关联模型.
例如,你可以这样做:
class DiscussionThread < ActiveRecord::Base
has_many :participations
has_many :participants, :through => :participations
end
class Participation < ActiveRecord::Base
belongs_to :discussion_thread
belongs_to :participant, :class_name => "User", :foreign_key => :user_id
end
class User < ActiveRecord::Base
has_many :participations
has_many :dicussion_threads, :through => :participations
end
Run Code Online (Sandbox Code Playgroud)
这给你三个表:
table: discussion_threads
columns: id
table: participations
columns: id | discussion_thread_id | user_id
table: users
columns: id
Run Code Online (Sandbox Code Playgroud)
要查找用户参与的线程,只需执行以下操作:
@user.discussion_threads
Run Code Online (Sandbox Code Playgroud)
并找到参与线程的用户:
@discussion_thread.participants
Run Code Online (Sandbox Code Playgroud)
注意:Thread是Ruby中的保留字,所以我重命名了它DiscussionThread
编辑
介绍一个如何序列化一组id然后查询它们的例子?
你在半夜醒来,在一种奇怪的强迫力下,你会去你的电脑并创建这种迁移:
rails g model Abomination horror_ids:text
Run Code Online (Sandbox Code Playgroud)
和型号:
class Abomination < ActiveRecord::Base
serialize :horror_ids
end
Run Code Online (Sandbox Code Playgroud)
您测试它以确保它可以存储数组:
@abomination = Abomination.create(:horror_ids=>[2,33,42])
@abomination.horror_ids # => [2,33,42]
Run Code Online (Sandbox Code Playgroud)
所以呢?你知道在幕后Rails将它转换为YAML,它看起来像这样:
---\n
- 2\n
- 33\n
- 42\n
Run Code Online (Sandbox Code Playgroud)
再次被强烈的催促迫使你想知道"我怎么能搜索存储在这个专栏中的特定ID?".嗯,这只是一个字符串,对吧?您知道如何在文本字段中找到它:
cthulhu = 33
Abomination.where(["horror_ids LIKE '%- ?\n%'",cthulhu]).first
Run Code Online (Sandbox Code Playgroud)
随着恐惧的增加,你会发现有人可能偶然发现这一点并认为这实际上是一个好主意.它必须被销毁!但你无法打字rm -rf *,相反,奇怪的力量会让你考虑到Cthulhu开发者未来的盲目追随者可能需要知道的怪癖,比如
@abomination = Abomination.create
@abomination.horror_ids # => nil
@abomination = Abomination.create(:horror_ids=>[])
@abomination.horror_ids # => []
@abomination = Abomination.create(:horror_ids=>"any string value can go here")
@abomination.horror_ids # => "any string value can go here"
Run Code Online (Sandbox Code Playgroud)
并且当列大小太小而无法容纳所有数据时,序列化数据可能会被破坏.
你做了最后的努力来踢出电源线,但为时已晚,控制你的喋喋不休,疯狂的意识将StackOverflow上的代码发布给全世界看.最后你崩溃陷入困境.第二天,你意识到你已经犯下了什么,你就永远放弃编码并成为一名会计师.
道德
不要这样做