【问题标题】:Create new records within a model method definition在模型方法定义中创建新记录
【发布时间】:2014-03-29 18:33:32
【问题描述】:

在控制器中,我试图通过find_contacts 方法查找联系人并将这些联系人设置为实例变量。我正在使用一个模块来查询返回 JSON 数据数组的 API。我想使用该 JSON 数据在数据库中创建新记录,然后将所有这些创建的记录返回给控制器。我的尝试

def find_contacts(params)
  found_contacts = API.query(params[:name], params[:job])
  # found_contacts array of json data [{data}, {data}]

  contacts = found_contacts.reduce([]) do |contacts, contact|
    contacts << Contact.create(contact)
  end
  return contacts
end

这是创建和返回记录的有效方式吗?

【问题讨论】:

  • 简化:contacts = found_contacts.map { |json| Contact.create(json) }

标签: ruby-on-rails json api model rails-activerecord


【解决方案1】:

你可以使用

contacts = Contact.create found_contacts

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2015-12-07
    • 2017-09-04
    • 1970-01-01
    相关资源
    最近更新 更多