javascript - AngularJS POST update to database in Rails -
i have app uses angularjs orders page, connects via json api sqlite3/ postrgres database in rails. can create , delete orders angular page, i'm having trouble updating column order shipped (a checkbox). when click on checkbox, js console indicates change of shipped value false
true
, returns error: post ... /orders/1.json 404(not found)
.
i think problem might code in rails orders_controller.
here code.
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
order model
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 devise_for :users, :controllers => { :registrations => "user_registrations" } resources :users resources :orders, only: [:index, :show, :create, :update, :destroy] resources :products resources :comments end root 'static_pages#index' '/search', to: 'static_pages#search' '/search_results', to: 'products#search_results' '/about', to: 'static_pages#about' '/contact', to: 'static_pages#contact' post 'static_pages/thank_you' devise_scope :user '/sign_up', to: 'devise/registrations#new' '/profile', to: 'devise/registrations#edit' end post '/payments/create', to: 'payments#create' 'payments/payment_thank_you', to: 'payments#payment_thank_you' end
from can tell, seems you're sending post
request update
action default, rails expecting put
or patch
request action.
however browser not support real http put
or patch
request via ajax, trick add, specific _method
posted json data.
{_method:'put', order: order_data }
ruby on rails - put method on update ajax
Comments
Post a Comment