ruby on rails我需要从api数据构建一个对象

问题描述 投票:0回答:2

我想从数据API创建一个对象。首先,用户必须输入他的immaticulation数字。一旦注册输入,他将在视图中返回以下数据

vehicles_controller:

   @vehicle = Vehicle.new
   @vehicles = []
    vehicle_number = params['immatricule'].capitalize
    vehicles.each do |vehicule|
    data_api = CarRegistrationFrance.Lookup(#{"vehicle_number"},"username","password")

Api_data response:

 => {"Description"=>"RENAULT CLIO IV", "RegistrationYear"=>"2017", "CarMake"=>{"CurrentTextValue"=>"RENAULT"}, "CarModel"=>{"CurrentTextValue"=>"CLIO IV"}, "EngineSize"=>{"CurrentTextValue"=>"4"}, "FuelType"=>{"CurrentTextValue"=>"DIESEL"}, "MakeDescription"=>{"CurrentTextValue"=>"RENAULT"}, "ModelDescription"=>{"CurrentTextValue"=>"CLIO IV"}, "Immobiliser"=>{"CurrentTextValue"=>""}, "IndicativeValue"=>{"CurrentTextValue"=>0}, "DriverSide"=>{"CurrentTextValue"=>""}, "BodyStyle"=>{"CurrentTextValue"=>"BERLINE 5 PORTES"}, "RegistrationDate"=>"2017-10-30","ExtendedData"=>{"anneeSortie"=>"2017", "boiteDeVitesse"=>"", "carburantVersion"=>"D", "carrosserieVersion"=>"", "classeSra"=>"K", "libVersion"=>"1.5 DCI 90 EDITION ONE EDC", "libelleModele"=>"CLIO IV", "marque"=>"RE", "modele"=>"88", "produit"=>"", "puissance"=>"4", "version"=>"", "cleCarrosserie"=>"", "groupeSra"=>"30", "nbPlace"=>"5", "datePremiereMiseCirculation"=>"30102017", "questionBatterie"=>"", "electrique"=>"", "genre"=>"", "typeVehicule"=>"", "numSerieMoteur"=>"VF15RBJ0D58888591", "valeurANeufSRA"=>"", "niveauRisqueVol"=>"", "protectionConstructeur"=>"", "puissanceDyn"=>"", "segmentVeh"=>""}} 
    @vehicles << data_api
    vehicle.description => data_api["Description"]
    vehicle.annee => data_api["RegistrationYear"]


    def vehicle_params
  params.require(:voiture).permit(:immatricule, :description, :annee)
end

一旦用户输入他想要加入的注册号码

data_api ["Description"] << vehicle ["description"]

将数据附加到车辆对象的属性

data_api ["RegistrationYear"] << vehicle ["year"]

/ user [:id] / vehicle / new是一个例子

<%= form_tag("/vehicle", method: "post") do %>
  <%= label_tag(:immatricule, "") %>
  <%= text_field_tag(:immatricule) %>
  <%= submit_tag("create") %>

/ user [:id] / vehicle /显示一个例子

<%= @vehicle.api_data["Description"] %>
<%= @vehicle.api_data["RegistrationYear"] %>
  1. 输入你的immatricule号码
  2. 将车辆用户的immatricule发布到api_data
  3. 从响应api数据创建对象车辆
  4. 渲染显示视图

我已经尝试了几次操作,但我找不到解决方案。

ruby-on-rails json api view controller
2个回答
0
投票

所以这种感觉就像你来自背景而不是CRUDCreate, Read, Update, Delete)意识到......基于你没有列出你正在努力实现这些东西的控制器等(对回答你的问题的任何回应至关重要)。

基于问题2/22 @ 06:18 am -600的状态,这里有一些快速说明......

你想要开始这个步骤 - RailsGuides

其次,我认为你列出的URL - 你有一个嵌套的路由,并使用匹配的嵌套模型。答案改变了我建议的控制器/动作/路由 - 所以在你试图理解这个答案之前一定要弄清楚你是不是......

所有这些都是猜测工作,因为我们缺少您的实现的详细信息(route.rb文件,如果这是您作为管理员正在调用的脚本或每个用户自己运行更新,如果这些东西都适用)。


一旦完成你要问的问题应该是......

“我应该使用哪种控制器和控制器操作来更新注册信息?” (通常显示为controller#action

CRUD的答案是update(rails称它为Edit来显示视图和update来执行)。

你抛出问题的原因是Rails Way(CRUD)已经拥有控制器的基本代码和该控制器动作更新字段的动作。您不必自己创建对象 - 所有永久性的数据对象都应该是Rails模型对象。

在你的情况下,Vehicle中的app/models/vehicle.rb模型将是我的猜测。您可以选择在config/routes.rb文件中为此路由嵌套为...

Rails.application.routes.draw do
  resources :users do
    resources :vehicle
  ...

哪个会给你一个"/{:user_id}/{:vehicle_id}/{controller action}"的路线/网址。

这假设......

  1. 用户通过Web或网络访问您的应用程序
  2. 他们注册或进入
  3. 显示来自API的信息(我不确定您是否希望将此信息反馈给该API,这就是您需要该对象的原因 - 但假设您不是这样)
  4. 用户#show控制器拉动车辆模型后从API中提取信息
  5. 你的控制器会将它们重定向到CRUD read动作(Rails称之为Show)。它也已经在控制器动作中编码以进行更新。

在你的情况下,这可能是... User#show,它将有accepts_nested_attributes_for :RegistrationYear:Description模型中的User,指的是你已经工作的Vehicle模型中的字段。


对于另一种情况......你只是包装另一个API,它正在更新,你的rails应用程序没有任何东西......

您需要一个用户实体或身份验证...也许您从您引用的API中获取omni_auth或其他安全登录令牌...所以您的步骤......

  1. 登录处理或您创建/登录用户
  2. 您的User#Show应该有一个指向Vehicle#Update的链接,或者User#Show视图应该包含带有用户和车辆ID的字段的表单...已经填写,因为控制器执行API查询提取所有信息并且有两个要更新的字段。
  3. 提交按钮应该在正常的rails应用程序中是另一个控制器#action的链接,它只是执行API的更新接口,而不是将信息存储到您自己的数据库中......尽管您可以轻松地将该API接口调用放入controller#action负责用于显示表格。

如果您只是使用自己的rails应用程序包装API,我建议您执行标准对象文件...

# depending on where you put this you might need to load it yourself
app/lib/other_api_connection.rb  

# rails prefers this format as part of ruby & it's class autoloading
class OtherAPI < CarRegistrationFrance
  attr_accessor :registration, :description


  def initialize(search_immat, user, pass, api_url = {whatever currently})
    ...
    @user = user 
    @pass = pass 
    @record = look_up
    @api_url = api_url 
  end

  def look_up(search_immat)
    ... 
    Lookup("#{search_immat}", @user, @pass)
  end

  def update_api
    begin
      ... {you haven't shown us the update API url} ...
    rescue {some error from api}
      return "{some error message}"
    end
  end
end

那么......你现在有了API处理程序对象......

使用时你可以在控制器#action中调用它...让我们说用户#显示,提交重定向到User#UpdateVehicle#Update

class Vehicle < ActionController::Base
  ...

  def update
    ... 

    # normal stuff probably needs to be deleted if you aren't saving to your application db THEN updating API (aka just wrapping an API - which I'm assuming you are doing since you haven't said otherwise & it's less work).
    # also you could pass the object as a parameter in the submit link - but that's not really CRUD per say
    @user = {whatever user is}
    api = OtherAPI.new(user, pass)

    # you might have to permit this as parameter to pull it out
    @response_code = api.update_api(:RegistrationYear, :Description) # or whole vehicle record if the API requires

    if @response_code == {whatever valid code is from that API documentation}
      format.html { redirect_to @vehicle, notice: 'Vehicle was successfully updated.' }
    else
      format.html { render :edit }
      format.json { render json: @vehicle.errors, status: :unprocessable_entity }
  end
  ... rest of controller actions
end

注意 - 我建议创建一个API接口类/对象,因为您可以从控制器或操作中调用代码,只需要在一个地方进行更改,如果更改了api url等等...但是你可能需要在include OtherAPI处每个控制器代码的顶部。


0
投票

你好,谢谢你的帮助

我使用设备来验证用户

my shemas database:

  create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.float "longitude"
t.float "latitude"
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "username"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.bigint "avatar_file_size"
t.datetime "avatar_updated_at"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true


 end

  create_table "vehicles", force: :cascade do |t|
    t.string "immatricule"
    t.string "description"
    t.string "marque"
    t.string "date_circulation"
    t.string "fuel_type"
    t.bigint "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id"], name: "index_vehicles_on_user_id"
  end

  add_foreign_key "vehicles", "users"

my model users:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, :trackable
         has_many :vehicles

my model vehicles:

class Vehicle < ApplicationRecord
  belongs_to :user
end

我需要这条路线:

   user_vehicles GET    /users/:user_id/vehicles(.:format)                                                       vehicles#index
                           POST   /users/:user_id/vehicles(.:format)                                                       vehicles#create
          new_user_vehicle GET    /users/:user_id/vehicles/new(.:format)                                                   vehicles#new
         edit_user_vehicle GET    /users/:user_id/vehicles/:id/edit(.:format)                                              vehicles#edit
              user_vehicle GET    /users/:user_id/vehicles/:id(.:format)                                                   vehicles#show
                           PATCH  /users/:user_id/vehicles/:id(.:format)                                                   vehicles#update
                           PUT    /users/:user_id/vehicles/:id(.:format)                                                   vehicles#update
                           DELETE /users/:user_id/vehicles/:id(.:format)                                                   vehicles#destroy

但我正在使用设计

在我的控制器中我需要构建具有响应的车辆api我需要在数据库中保存数据从数字immatricule形式新车辆用户输入number_immatricule“immatricule”=形成新车辆[:immatricule]用户表格获取data_api

def build_vehicle_user_from_api_data
"description" == data_api["description"]
 "marque" == data_api["CarMake"]
"date_circulation" == data_api["RegistrationDate"]
 "fuel_type" == data_api["fuel_type"]
end

我正在寻找如何在我的控制器用户或车辆中做到这一点

© www.soinside.com 2019 - 2024. All rights reserved.