Rails:建立关系之间的差异 [英] Rails: build for difference between relationships
问题描述
一个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.
我想对edits
和articles
中都存在的: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屋!