首页 > 解决方案 > 如何将参数传递给rails中的两个不同的表

问题描述

作为一个新手,我开始做 API POC。我的情况如下所述:

我有具有 create 方法的 seekerController。我希望当一个 Post 请求发出时,很少有参数需要进入 seeker 表,很少需要进入 profile 表(这个表也有 seekerID 列)。我想在事务提交中做到这一点。所以阅读后我开始做以下事情: -

ActiveRecord::Base.transaction do
          seeker = Seeker.new(seeker_params)
          seeker.save!
          params[:seeker_id] = seeker[:id]

          seekerprofile = SeekerProfile.new(seekerprofile_params)
          seekerprofile.save!
          end
      render json: {status: 'success', message: 'Request is processed successully', data:seeker},status: :created;

我有以下定义:(我怀疑以下方式是否正确)

def seeker_params
    params.require(:seeker).permit(:username, :alias, :mobile_number, :country_code, :email_address, :description, :status)
  end
  def seekerprofile_params
    params.require(:seeker_profile).permit(:seeker_id, :first_name, :middle_name, :last_name, :date_of_birth, :pincode, :building_name, :address, :email_address, :description, :status)

  end

让我在这里直截了当地提出我的问题:-我有如下的 post body 请求参数:

{
      "username" : "TestName12",
      "alias" :  "TestAlia12",
     #above should go to seeker table
      "first_name":"xyz",
      "Last_Name":"abc"
      #above should go above Seekerprofile table. seekerprofile has seekerid also.
} 

我的模型如下:-

> class SeekerProfile < ApplicationRecord
> 
>   belongs_to :seeker end

我已经尝试了我在开始代码中发布的内容,但由于 seekerprofile_params 为空,我收到错误消息。所以我确信我的方法是错误的。

谁能提供示例代码,如何做到这一点?我是 java 人,对 ruby​​ 来说更新鲜。

标签: ruby-on-railsruby-on-rails-3

解决方案


由于所提供的信息有限,似乎问题可能与seeker_id结果中的字段为空白有关seekerprofile_params。基本上,我们设置params[:seeker_id]params[:seeker_id] = seeker[:id]保存后Seeker。但是在为创建创建参数时SeekerProfile,我们使用seekerprofile_paramswhich 寻找seeker_idinparams[:seeker_profile][:seeker_id]因为我们params.require(:seeker_profile)在允许之前使用seeker_id。由于SeekerProfile没有得到 a seeker_id,因此可能无法保存,具体取决于模型的设置方式。
但是,如果您尝试同时创建 aSeeker和 a SeekerProfile,您可能需要检查Rails 中的嵌套属性

收到更多输入后编辑:

考虑到 API 合约无法更改且需要维护,可以使用以下方法创建 aseeker和 a seeker_profile
1)我们可以更改模型Seeker以接受嵌套属性,SeekerProfile如下所示:

# app/models/seeker.rb

has_many :seeker_profiles  # As mentioned in the question comments
accepts_nested_attributes_for :seeker_profiles

2)然后可以将控制器代码更改如下:

# app/controllers/seeker_controller.rb

def create
  seeker = Seeker.new(creation_params)
  seeker.save!

  render json: {status: 'success', message: 'Request is processed successully', data:seeker},status: :created
end

private

def creation_params
  params.permit(:username, :alias).merge(seeker_profiles_attributes: [seeker_profile_creation_params])
end

def seeker_profile_creation_params
  params.permit(:first_name, :last_name)
end

这里发生的事情基本上是我们允许模型在创建期间seeker接受属性。seeker_profiles模型使用属性编写器接受这些属性seeker_profiles_attributes。由于关系是一种has_many关系,因此seeker_profiles_attributes接受一个对象数组,其中每个哈希对象代表一个seeker_profile要创建的子对象。
在上面提到的代码中,我假设只seeker_profile创建一个。如果您的 API 发生变化并希望在创建过程中接受多个配置文件,我会让您自己弄清楚,并保证您可以在遇到困难时返回评论。
还有一点需要注意的是,ActiveRecord::Base.transactionblock 不是必需的,因为任何正在创建的对象的失败都会回滚整个事务。


推荐阅读