Rails:建立关系之间的差异 [英] Rails: build for difference between relationships

查看:82
本文介绍了Rails:建立关系之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个doc有很多articles可以有很多edits.

A doc has many articles and can have many edits.

我想为每个article建立一个edit,最多达到@doc.articles个总数.该代码适用于第一个版本(即尚无edits的情况).

I want to build an edit for each article up to the total number of @doc.articles. This code works with the first build (i.e., when no edits yet exist).

def editing
  @doc = Doc.find(params[:id])
  unbuilt = @doc.articles - @doc.edits
  unbuilt.reverse.each do |article|
    @doc.edits.build(:body => article.body, :article_id => article.id, :doc_id => @doc.id)
  end
end

但是,当edits已经存在时,它将保留那些edits并仍然为@doc.articles进行构建,最终会导致edits过多,如果仅更改一个article,则会导致某些重复.

But when edits already exist it'll keep those edits and still build for the @doc.articles total, ending up with too many edits and some duplicates if only one article was changed.

我想对editsarticles中都存在的:article_id提出一些条件,以说(在 pseudocode 中):

I want to put some condition against :article_id which exists in both edits and articles in to say (in pseudocode):

unbuilt = @doc.articles - @doc.edits
unbuilt.where('article_id not in (?)', @doc.edits).reverse.each do |article|
  @doc.edits.build(...)
end

任何帮助都是非常好的!非常感谢.

Any help would be excellent! Thank-you so much.

推荐答案

您在这里做的事情很奇怪:

You are doing something weird here:

unbuilt = @doc.articles - @doc.edits

您可能想要这个

unbuilt = @doc.articles - @doc.edits.map(&:article)

如果@ doc.articles和@ doc.edits是小的集合,则此方法有效,否则将首选SQL解决方案.

This works if @doc.articles and @doc.edits are small collections, otherwise a SQL solution would be preferred.

-添加了说明-

这片红宝石

@doc.edits.map(&:article)

等同于

@doc.edits.map do |edit| edit.article end

上一个更紧凑,并利用了ruby 1.9中引入的功能

the previous one is much more compact and exploits a feature introduced in ruby 1.9

它基本上采用一个符号(:article),在其上调用'to_proc'方法(通过使用'&'字符来实现).您可以将'to_proc'方法视为与此类似的东西:

It basically takes a symbol (:article), calls on it the 'to_proc' method (it does this by using the '&' character). You can think of the 'to_proc' method as something very similar to this:

def to_proc
  proc { |object| object.send(self) }
end

在ruby中,块和proc通常等效(kindof),因此可以正常工作!

In ruby, blocks and procs are generally equivalent (kindof), so this works!

这篇关于Rails:建立关系之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆