Ruby-on-rails Rails 4 按方法查找或创建不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22520274/
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 23:27:44  来源:igfitidea点击:

Rails 4 find or create by method doesn't work

ruby-on-railsruby-on-rails-4associations

提问by userails

I have a one to many association between jobs and companies and it works fine. In the job form view I have text_field for the company name with an autocomplete feature. The autocomplete works fine but the find_or_create_by don't create a new company if I put a company name that doesn't exist in the autocomplete list.

我在工作和公司之间建立了一对多的关联,而且效果很好。在工作表单视图中,我有带有自动完成功能的公司名称的 text_field。自动完成工作正常,但如果我在自动完成列表中输入不存在的公司名称,则 find_or_create_by 不会创建新公司。

  def company_name
    company.try(:name)
  end

  def company_name=(name)
    @company = Company.find_or_create_by(name: name)
  end

回答by eronisko

Please take a look at this answer.

请看看这个答案

What used to be

曾经是什么

@company = Company.find_or_create_by_name(name)

in Rails 4 is now

在 Rails 4 中

@company = Company.find_or_create_by(name: name)

Another way to do this in Rails 4 would be:

在 Rails 4 中执行此操作的另一种方法是:

@company = Company.where(name: name).first_or_create

回答by Kalpesh Fulpagare

Company.find_or_create_by(name: name)

It should work out of the box. Only thing that can prevent it from creating record is validation errors.

它应该是开箱即用的。唯一可以阻止它创建记录的是验证错误。

Try this in rails consoleto check if its working or not. And check the validation errors as well.

试试这个rails console来检查它是否工作。并检查验证错误。

name = "YOUR TEXT FOR NAME ATTRIBUTE"
c = Company.find_or_create_by(name: name)
puts c.errors.full_messages

回答by uma

This method is deprecated in rails 4.

此方法在 rails 4 中已弃用。

Rails4 release message:

Rails4 发布消息:

Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do.

弃用旧式基于散列的查找器 API。这意味着以前接受“查找程序​​选项”的方法不再适用。

It is deprecated method, but it should work. Maybe, Rails is not supporting it now.

这是不推荐使用的方法,但它应该可以工作。也许,Rails 现在不支持它。

You can get more info click hereand check 11.2 Deprecations.

您可以获得更多信息,点击这里查看11.2 Deprecations