【问题标题】:Saving an array of params in Rails在 Rails 中保存参数数组
【发布时间】:2016-02-24 22:38:07
【问题描述】:

我的 Rails 5 api 项目中有两个模型:Places 和 Beacons(Place has_many Beacons,外键:place_id)。这个 API 接受 JSON,比如这个:

{
  "place":{
    "name": "bedroom"
  },
  "beacon":{
    "SSID": "My Wi-Fi",
    "BSSID": "00:11:22:33:44:55",
    "RSSI": "-55"
  }
}

这个 JSON 工作得很好,有这些类:

def create
    @place = Place.new(place_params)
    @beacon = Beacon.new(beacon_params)


    if @place.save
      @beacon.place_id=@place.id
      if @beacon.save
        render :json => {:place => @place, :beacon => @beacon}, status: :created, location: @places
      else
        render json: @beacon.errors, status: :unprocessable_entity
      end
    else
      render json: @place.errors, status: :unprocessable_entity
    end
end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_place
      @place = Place.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def place_params
      params.require(:place).permit(:name)
    end

  def beacon_params
    params.require(:beacon).permit(:SSID, :BSSID, :RSSI)
  end

但是,我希望它以数组中的同一 JSON 传递多个 Beacons 对象(甚至根本没有信标)。如何将所有信标保存在参数数组中并生成包含所有信标的响应?

【问题讨论】:

    标签: ruby-on-rails json activerecord ruby-on-rails-5


    【解决方案1】:

    我假设地点 has_many :beacons。如果是这样,您可以使用嵌套属性。这使您可以分配和更新嵌套资源,在本例中为 Beacons。首先,在您的 Place 模型中:

    accepts_nested_attributes_for :beacons
    

    然后,更改控制器中的 place_params 方法以允许信标的嵌套属性:

    def place_params
      params.require(:place).permit(:name, beacons_attributes: [:id, :SSID, :BSSID, :RSSI])
    end
    

    还有你的 json:

    {
      "place":{
        "name": "bedroom",
        "beacons_attributes": [
          {
            "SSID": "My Wi-Fi",
            "BSSID": "00:11:22:33:44:55",
            "RSSI": "-55"
          }, { 
            //more beacons here 
          }
        ]
      },
    
    }
    

    您可以拥有零个、一个或多个信标,如果您包含信标的 ID,则在更新时也可以这样做。

    您也不必手动创建@beacon,只需执行以下操作:@place = Place.new(place_params),它会自动创建信标并将它们关联到 Place。

    如果您想了解更多信息或澄清,可以在此处阅读更多信息:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

    编辑:我错过了您询问如何在响应中包含信标的地方。最快的方法是将其包含在 json 渲染中:

    render :json => @place.to_json(:include => :beacons)
    

    您可以使用 Active 模型序列化程序 (https://github.com/rails-api/active_model_serializers)、jbuilder (https://github.com/rails/jbuilder),或者更简单地说,只需覆盖模型上的 to_json 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      相关资源
      最近更新 更多