Ruby on rails 基于嵌套对象的存在,对中的关联进行修改有很多步骤
一段时间以来,我一直在努力寻找解决问题的最佳方法。 我有一个has-many-through模型,其中列表包含许多单词,单词可以在许多列表中。 关联表是一个单词列表 我正在为:单词使用accepts\u嵌套的\u attributes\u 单词作为嵌套属性通过列表控制器提交 然而,我想要实现的逻辑是: 如果用户修改了一个单词,我不希望该单词发生任何变化 其他引用该词的列表。 如果用户修改了一个单词,而它是一个新词,则创建一个单词并将其关联到用户列表。 如果用户修改了一个单词并且它存在,则更改关联。 如果用户添加了一个单词,而该单词已经存在,那么只需添加 协会 如果用户添加的单词不存在,请添加该单词 去收藏。 为了实现这一点,我在列表模型中编写了一个create_或_associate模块。这是可行的,但我强烈感觉有更好的方法Ruby on rails 基于嵌套对象的存在,对中的关联进行修改有很多步骤,ruby-on-rails,activerecord,ruby-on-rails-4,Ruby On Rails,Activerecord,Ruby On Rails 4,一段时间以来,我一直在努力寻找解决问题的最佳方法。 我有一个has-many-through模型,其中列表包含许多单词,单词可以在许多列表中。 关联表是一个单词列表 我正在为:单词使用accepts\u嵌套的\u attributes\u 单词作为嵌套属性通过列表控制器提交 然而,我想要实现的逻辑是: 如果用户修改了一个单词,我不希望该单词发生任何变化 其他引用该词的列表。 如果用户修改了一个单词,而它是一个新词,则创建一个单词并将其关联到用户列表。 如果用户修改了一个单词并且它存在,则更改关联
def create_or_associate
# For each word submitted
self.words.each do |the_list|
if the_list.word_changed? #(New and Changed)
if the_list.id.nil? #new list word
if Word.exists?(word: the_list.word)
self.words << Word.where(word: the_list.word)
else
#new list word not in DB
self.words << the_list
end
else
# a changed list word
if Word.exists?(word: the_list.word)
# changed word already in DB
self.words << Word.where(word: the_list.word)
self.words.find(the_list.id).delete
else
#changed word not in DB
new_word=Word.create(word: the_list.word)
self.words << new_word
self.words.find(the_list.id).delete
end
end
end
end
end
我在旅行中没有看到任何类似的代码,这给我敲响了警钟,也许我没有走上正确的轨道
感谢您的帮助我可能会使用这种方法
words = params[:some_word_list]
@list = List.new # List.find() if you're updating
@list.words = [] if @list.persisted?
words.each do |w|
word = Word.find_or_create_by(:word => w)
@list.words << word
end
@list.save
希望能有所帮助非常感谢。所以基本上每次都要重新创建关联。