简体   繁体   English

Ruby Rails在模型中插入ActiveRecord查询

[英]Ruby Rails insert ActiveRecord query in my model

So I'm trying to perform a query of "SpiritTrial" model where "trlid" have 7th and 8th digit = "TI", then I want to insert the objects it finds into model TiTrial and I would like to take the "trlid" from the SpiritTrial model and redefine it as "name" in TiTrial. 因此,我尝试执行“ SpiritTrial”模型的查询,其中“ trlid”的第7位和第8位=“ TI”,然后我要将其找到的对象插入模型TiTrial中,我想使用“ trlid”从SpiritTrial模型中重新定义,并在TiTrial中将其重新定义为“名称”。 Here's where I'm at in TiTrial.rb I'm getting the right stuff back I'm just having a hard time translating the documentation out there in to what I need it to do....any help is super appreciated as always. 这就是我在TiTrial.rb所处的位置,我正在找回正确的东西,我只是很难将那里的文档翻译成我需要它做的事情。...一如既往地非常感谢任何帮助。

def spiritpull
  u = SpiritTrial.where("trlid LIKE (?)", "%%%%%%TI%")

end

I suggest to you to use a sql function, It depends you DMNS, sometimes ActiveRecord is not the best option to perform sql, I think you should create a function that perform your query and insert in your table. 我建议您使用sql函数,这取决于您DMNS,有时ActiveRecord不是执行sql的最佳选择,我认为您应该创建一个函数来执行查询并插入到表中。 I recommend to you keep tracking your sql using a migration like this http://www.rigelgroupllc.com/blog/2014/09/14/working-with-complex-sql-statements/ 我建议您使用这种迁移方式(例如http://www.rigelgroupllc.com/blog/2014/09/14/working-with-complex-sql-statements/

If I understand correctly: 如果我正确理解:

def spiritpull
  u = SpiritTrial.where("trlid LIKE (?)", "%%%%%%TI%")
  # you should have multiple u results, iterate through each
  u.each do |spirit|
    # create a new TiTrial for each spirit
    r = TiTrial.new(name: spirit.trlid)
    # don't forget to save
    r.save
  end
end

Take each SpiritTrial and create a new TiTrial per my above comments. 进行每个SpiritTrial并根据我的上述评论创建一个新的TiTrial。 Let me know if I'm missing something. 让我知道我是否想念一些东西。

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

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