[英]In Ruby on Rails, if a note has many tags, how do I check if a note has any tags?
I tried note.tags.nil?, but it didn't work. 我尝试了note.tags.nil ?,但是没有用。 How do I do this?
我该怎么做呢? Thanks for reading.
谢谢阅读。
如果您想知道@note
是否具有任何关联的tags
,可以使用
@note.tags.empty?
You can call @note.tags.any?
您可以致电
@note.tags.any?
to test if there are any tags. 测试是否有任何标签。 Note that this will hit the database to do a count.
请注意,这将对数据库进行计数。 You might want to left join when pulling out
@note
, to save this query. 您可能希望在拉出
@note
时@note
,以保存此查询。 Eg.: 例如。:
Note.first(:select => 'notes.*, case when tags.id is not null then 1 else 0 end as has_any_tags', :joins => "LEFT JOIN tags ON tags.note_id = notes.id")
Your Note
model will now have a field has_any_tags
that is either 0
(false) or 1
(true), if there are any related tags. 现在,如果有任何相关标签,则您的
Note
模型将具有一个has_any_tags
字段,该字段为0
(假)或1
(真)。
You can move the query options above into a default scope and wrap the field up in an accessor: 您可以将上面的查询选项移至默认范围,并将字段包装在访问器中:
class Note
has_many :tags
default_scope :select => 'notes.*, case when tags.id is not null then 1 else 0 end as has_any_tags', :joins => "LEFT JOIN tags ON tags.note_id = notes.id"
def has_any_tags?
has_any_tags == "1"
end
end
Now, it all happens transparently: 现在,这一切都是透明的:
>> Note.first.has_any_tags?
=> true
In Addition, you could think about having a counter cache column for Tags. 此外,您可以考虑为标签添加一个计数器缓存列。 With that
:tags_count
you wouldn't need another SQL query. 有了
:tags_count
您就不需要另一个SQL查询了。 You could check then with @note.tags_count == 0
, @note.tags_count.zero?
您可以使用
@note.tags_count == 0
来检查, @note.tags_count.zero?
or whatever you like. 或任何你喜欢的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.