简体   繁体   English

获取关联的rails模型的索引

[英]Get the index of an associated rails model

I'm trying to set a default value for a rails model based on the number of siblings it has relative to an associated model. 我正在尝试根据相对于关联模型的兄弟姐妹数量为rails模型设置默认值。 I've managed to get it working like this; 我设法让它像这样工作;

class Comment < ActiveRecord::Base

  belongs_to :post

  after_initialize :set_defaults  

  def set_defaults             
    comment_index = self.post.comments.count
    self.title ||= "Default title for comment #{comment_index}"  
  end
end 

But this is going to go back to the database and count the posts every time a new comment is saved and I'm trying to save on database calls. 但是这将返回到数据库并在每次保存新注释时计算帖子并且我正在尝试保存数据库调用。 I was wondering if there is something already within rails that would perform this kind of functionality? 我想知道在rails中是否有某些功能可以执行这种功能? I had a quick look through the API but it didn't turn up anything. 我快速浏览了API,但它没有发现任何东西。 Does anyone know? 有人知道吗?

The rails counter cache feature (you can learn about it here - http://railscasts.com/episodes/23-counter-cache-column ) can help with fetching the current comments count without counting them over and over again. rails counter cache功能(您可以在这里了解它 - http://railscasts.com/episodes/23-counter-cache-column )可以帮助获取当前的注释计数,而无需一遍又一遍地计算它们。 But it won't save you the DB call to find the relevant post. 但它不会为您节省DB调用以找到相关帖子。

Also, note that both your current implementation and with counter cache you might end up with two or more comments having the same index and also inconsistent indexing (newer records having lower indexes than older ones), if you allow deletion of comments. 此外,请注意,如果允许删除注释,则当前实现和计数器缓存最终可能会导致两个或多个具有相同索引的注释以及索引不一致(索引较旧的记录的索引更低)。 If the latter is a problem, you can use the last comment's index to have more consistent indexing, or by caching the comments count in the parent post without decreasing the number when a comment is deleted. 如果后者是一个问题,您可以使用最后一个注释的索引来获得更一致的索引,或者通过缓存父帖子中的注释计数而不减少删除注释时的数字。

Finally, if the comment index is for display only (like numbering the comments in the post page) you can do it on the frontend side. 最后,如果评论索引仅用于显示(如在帖子页面中对评论进行编号),则可以在前端进行。 just render the comments by id or creation date and give each an index dynamically. 只需按id或创建日期呈现注释,并动态地为每个注释。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM