有没有办法将方法委托给“主动”连接模型?

时间:2011-10-10 17:37:06

标签: ruby-on-rails activerecord associations

假设我有帖子,这些帖子通过分类有很多类别。假设我向primary添加了一个布尔列categorizations,以确定帖子的主要类别。但是现在我处理连接模型时,我真正喜欢的是这样的事情:

post = Post.first
primary_cat = post.categories.where(:primary => true)

post.categories.first.primary = true
post.save # would actually update the categorization, setting primary = true

我可以给你各种各样的例子来说明为什么这会有用,但基本上我希望能够与模型进行交互,就像它以某种方式与其连接模型合并一样。能够说“什么是主要类别?”或“好的,这个类别将是主要的”,没有触及连接模型对我来说是直观的想法。

Rails甚至可以实现这一点吗?有没有人看过以前做过这种事情的努力?

4 个答案:

答案 0 :(得分:1)

简短的回答是在类别上创建一个set_primary(post)方法,该方法将post和boolean作为参数。

def set_primary(post)
  categorization = post.categorization.where('your opts hash here')
  categorization.primary = true
  categorization.save!
end


post.categories.first.set_primary(post)

答案 1 :(得分:1)

Charlie Bowman确实在Category模型上使用set_primary逻辑进行了第一部分拼图,但是他的setter并没有取消之前的活动类别...此外,史蒂夫问题的昂贵部分实际上只是得到了每个请求的主要类别。为了解决这个问题,我还会在Post上保存主类别ID。这样您就不需要访问连接模型来确定主要类别。

def set_primary_category(post)
  post.categorizations.each do |cat|
    if cat.post == post
      cat.primary = true
      cat.save!
      post.update_attribute(:primary_category_id, cat.category_id)
    else
      cat.update_attribute(:primary, false) if cat.primary
    end
  end
end

设置:

post.categories.first.set_primary(post)

访问:

post.primary_category

不幸的是,我认为没有人制造出一个让你更容易完成的宝石,但逻辑非常简单。它还具有访问分类和帖子中的主要状态的好处,因此您始终可以快速访问数据。

另外,我认为很好记住。你有很多关系的帖子/类别。但是post / primary_category只有一个has_one关系。每当你有这样的访问模式时,我都想尝试远离has_one的连接模型,因为它不是必需的。

答案 2 :(得分:1)

我喜欢任务的解决方案,除了设置它应该只是post.primary_category=并且应该采用类别对象。只需在帖子上设置has_one :primary_category就可以了。

答案 3 :(得分:-1)

此问题可能与Ruby on Rails: attr_accessor for submodels重复,但基本上delegate应该是您正在寻找的内容,并在保存时附加回调。