Ruby/Rails - 检查子 ID 是否存在于 HABTM 关系记录中
我有一组名为“任务”和“帖子”的资源,并且彼此之间存在 has_and_belongs_to_many (HABTM) 关系。
还有一个连接它们的值的连接表。
create_table 'posts_tasks', :id => false do |t|
t.column :post_id, :integer
t.column :task_id, :integer
end
所以我的问题是如何检查从 @post.tasks 创建的数组中是否存在特定任务的 id?
irb(main):011:0> @post = Post.find(1)
=> #<Post id: 2, comment: "blah blah", created_at: "2011-10-18 03:40:30", updated_at:
irb(main):012:0> @post.tasks
=> [#<Task id: 1, description: "Test 1", created_at: "2011-10-18 03:
22:05", updated_at: "2011-10-18 03:22:05">, #<Task id: 3, description: "Test 3",
created_at: "2011-10-18 03:22:21", updated_at: "2011-10-18 03:22:21
">]
所以我的问题是 ruby 的编写方式是什么“@task = Task.find(2)”是否存在于 @post.tasks 中,如果存在则返回 true 或 false?
I have a set of resources called Tasks and Posts and there are in a has_and_belongs_to_many (HABTM) relationship with each other.
There is also a join table connecting their values.
create_table 'posts_tasks', :id => false do |t|
t.column :post_id, :integer
t.column :task_id, :integer
end
So my question is how do I check to see if the id of a specific task exists within the array created from @post.tasks?
irb(main):011:0> @post = Post.find(1)
=> #<Post id: 2, comment: "blah blah", created_at: "2011-10-18 03:40:30", updated_at:
irb(main):012:0> @post.tasks
=> [#<Task id: 1, description: "Test 1", created_at: "2011-10-18 03:
22:05", updated_at: "2011-10-18 03:22:05">, #<Task id: 3, description: "Test 3",
created_at: "2011-10-18 03:22:21", updated_at: "2011-10-18 03:22:21
">]
So my question is whats the ruby way for writing does "@task = Task.find(2)" exist within @post.tasks and if so return true or false?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
与 Gabelsman 的建议相比要轻得多。
Is much lighter compared to what Gabelsman has suggested.
其中
task_id
是您要检查的任务的 ID。为了稍微解释一下这一点,您将获取任务列表,将它们映射到其 id 数组,然后检查有问题的 id 是否在该数组中。如果您不熟悉map
,您应该查看一下,它非常棒。ruby-docs
Where
task_id
is the id of the task you want to check. To explain this a little bit, you're taking the list of tasks, mapping them to an array of their ids, and then checking to see if the id in question is in that array. If you're not familiar withmap
you should check it out, it's awesome.ruby-docs
假设您将
has_and_belongs_to_many
命名为:posts
,那么在 Rails 中执行类似的操作是非常优化的:@post.task_ids.include?(task.id)
我注意到这里提供的两个答案导致
n
select 语句。但使用task_ids
执行此操作会缓存第一个查询,其余查询不需要来自数据库的SELECT
语句。Assuming you named your
has_and_belongs_to_many
to:posts
then doing something like this in Rails is very optimized:@post.task_ids.include?(task.id)
I noticed that the two answer provided here result in
n
select statements. But doing it withtask_ids
caches the first query and the rest does not require aSELECT
statement from the DB.您可以使用 exists? 方法:
You can use exists? method for that: