AngularJS POST更新到Rails中的数据库

时间:2016-07-28 09:11:48

标签: javascript sql ruby-on-rails angularjs json

我有一个使用AngularJS作为Orders页面的应用程序,它通过JSON API连接到Rails中的SQLite3 / Postrgres数据库。我可以从Angular页面创建和删除订单,但是我在更新订单发货列时遇到问题(复选框)。当我单击复选框时,JS控制台会指示从falsetrue的已发货值的更改,但随后会返回错误:POST ... /orders/1.json 404(Not Found)

我认为问题可能出在Rails orders_controller中的代码中。

这是我的代码。

index.html.erb

<input type="checkbox" value="order.shipped" ng-click="changeShipped(order)">

app.js

// change shipped status via checkbox
$scope.changeShipped = function(order) {
  order.shipped = !order.shipped;
  models.orders.save(order); // returns POST... 404 (Not Found)
  console.log(order.shipped);  // indicates true / false
}

orders_controller.rb

class OrdersController < ApplicationController
  protect_from_forgery
  skip_before_action :verify_authenticity_token, if: :json_request?
  respond_to :json, :html
  load_and_authorize_resource

def index
  @user = current_user
  @orders = Order.all.to_json(:include => [{:product => {:only => :title}}, {:user => {:only => :email}}])
  respond_with @orders  
end

def show
  @order = Order.find(params[:id]).to_json(:include => [{:product => {:only => :title}}, {:user => {:only => :email}}])

# def new
# end

def create
  @order = Order.create(order_params)
  respond_with @order
end

def update
  @order = Order.find(params[:id])
  respond_with @order
end

def destroy
  respond_with Order.destroy(params[:id])
end

protected

def json_request?
  request.format.json?
end

private
def order_params
  params.require(:order).permit(:product_id, :user_id, :total, :shipped)
  end
end

订单型号

t.integer "user_id"
t.integer "product_id"
t.decimal   "total"
t.boolean "shipped",    default: false, null: false
t.index ["product_id"], name: "index_orders_on_product_id"
t.index ["user_id"], name: "index_orders_on_user_id"

的routes.rb

Rails.application.routes.draw do
  devise_for :users, :controllers => { :registrations =>  "user_registrations" }
  resources :users
  resources :orders, only: [:index, :show, :create, :update, :destroy]

  resources :products do
   resources :comments
  end

  root 'static_pages#index'

  get '/search', to: 'static_pages#search'

  get '/search_results', to: 'products#search_results'

  get '/about', to: 'static_pages#about'

  get '/contact', to: 'static_pages#contact'

  post 'static_pages/thank_you'

  devise_scope :user do
    get '/sign_up', to: 'devise/registrations#new'
    get '/profile', to: 'devise/registrations#edit'
  end

  post '/payments/create', to: 'payments#create'
  get 'payments/payment_thank_you', to: 'payments#payment_thank_you'
end

1 个答案:

答案 0 :(得分:1)

据我所知,您似乎正在向POST操作发送update请求,但默认情况下,rails期待PUT或{{1}请求该行动。

然而,大多数浏览器不支持通过ajax发送真正的http PATCHPUT请求,因此诀窍是为发布的json数据添加特定的PATCH

_method Ruby on rails - PUT method on update ajax