ruby on rails find_or_initialize

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12319832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:42:58  来源:igfitidea点击:

ruby on rails find_or_initialize

ruby-on-railsrubyruby-on-rails-3

提问by joe nayyar

Is there any better way to achieve this in Ruby on Rails?

有没有更好的方法在 Ruby on Rails 中实现这一点?

I'm searching for 11 fields and all are required also, and if not found initialize it.

我正在搜索 11 个字段,所有字段也是必需的,如果没有找到,则对其进行初始化。

There will be more required fields adding to it.

将有更多必填字段添加到其中。

This query works perfect for me, but it just doesn't look like the best way to do this.

这个查询对我来说很完美,但它看起来并不是最好的方法。

find_or_initialize_by_make_and_country_and_engine_and_power_and_body_and_doors_and_fuel_and_cylinders_and_transmission_and_gears_and_wheels(model,country,engine,power,body, doors, fuel, cylinders, transmission,gears,wheels)

回答by Filipe Giusti

On rails 3.2 I would do

在 Rails 3.2 上我会做

attributes = {}
Model.where(attributes).first_or_initialize

Documentation http://apidock.com/rails/ActiveRecord/Relation/first_or_initialize

文档http://apidock.com/rails/ActiveRecord/Relation/first_or_initialize

回答by moger777

Considering the sheer number of fields you are using, you probably are better off manually finding the record and initializing it if it does not exist:

考虑到您使用的字段数量庞大,如果记录不存在,您最好手动查找并初始化它:

attributes = {
  country: country,
  engine: engine,
  power: power,
  body: body
  etc ...
}

record = where(attributes).first
record = new(attributes) unless record

回答by Boat Pathompon

You can define method like this in your model

您可以在模型中定义这样的方法

def self.find_or_initialize_by_field(params)
    send("find_or_initialize_by_#{params.keys.join("_and_")}", *params.values)
end

and then you can call this method like

然后你可以像这样调用这个方法

YourModel.find_or_initialize_by_field({country: country, engine: engine})

回答by Pritesh Jain

while using find_or_intialize_by

使用时 find_or_intialize_by

find by key fields , dont assign all the feilds at once

按关键字段查找,不要一次分配所有字段

eg I assume the make is the key field in the model

例如,我假设 make 是模型中的关键字段

car = find_or_initialize_by_make(model)

car.update_attributes(country: country,engine: engine,power: power, body: body,doors: doors ,fuel: fuel,cylinders:cylinders,transmission: transmission, gears: gears, wheels: wheels)

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Dynamic+attribute-based+finders

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Dynamic+attribute-based+finders