简体   繁体   中英

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. 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.

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. 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/

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. Let me know if I'm missing something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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