我有一个应用程序使用AngularJS的订单页面,它通过JSON API连接到我的SQLite3/Postrgres数据库在Rails中。我可以从Angular页面创建和删除订单,但是我无法更新订单发货列(复选框)。当我点击该复选框时,JS控制台会指示出货值从false
更改为true
,但它会返回错误:POST ... /orders/1.json 404(Not Found)
。AngularJS POST更新到数据库在Rails
我认为这个问题可能与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
你能不能也发表您的路线? – Finks
当然,见上面 – Christian