Im working on my Rails Backend in Ruby and i want to post Data to this server. But if i do a Post-request with PAW i get redirected. Im a newbie to Http Requests. Could someone explain me the functionality and how to use http post requests?
i want to post information on my server's datanase (sqlite3).
Here's a screenshot which should explain everything:
how does this work? please explain :)
thanks.
greetings John
and here's the code:
OwnersController:
#app/controllers/owners_controller.rb
class OwnersController < SessionsController
respond_to :html
before_action :owner_find, only: [:show, :edit, :update, :destroy]
def index
#owners = Owner.all
end
def show
end
def update
#owner = Owner.find(params[:id])
if #owner.update(owner_params)
redirect_to #owner
else
render 'edit'
end
end
def new
#owner = Owner.new
end
def destroy
#owner.destroy
redirect_to owners_path
end
def edit
end
def create
#owner = Owner.new owner_params
if #owner.save!
flash[:notice] = 'You signed up successfully'
flash[:color]= 'valid'
redirect_to owners_path
else
flash[:notice] = 'Form is invalid'
flash[:color]= 'invalid'
render 'new'
end
end
private
def owner_find
#owner = Owner.find(params[:id])
end
def owner_params
params.require(:owner).permit(:name, :password, :password_confirmation, :token)
end
end
SessionController:
class SessionsController < ApplicationController
before_filter :authenticate_user, :except => [:login, :login_attempt]
def login
#goes to Login Form
end
def logout
session[:owner_id] = nil
redirect_to :action => 'login'
end
def login_attempt
authorized_user = Owner.authenticate_by_name(params[:login_name],params[:login_password])
if authorized_user
session[:owner_id] = authorized_user.id
flash[:notice] = "Wow Welcome again, you logged in as #{authorized_user.name}"
redirect_to welcome_index_path
else
flash[:notice] = 'Invalid Username or Password'
flash[:color]= 'invalid'
render 'login'
end
end
end
Console Logs:
from web-request (http://192.168.2.144:3000/owners?name=hans&password=hans321&password_confirmation=hans321)
Started GET "/owners?name=hans&password=[FILTERED]&password_confirmation=[FILTERED]" for 192.168.2.144 at 2015-10-01 12:12:18 +0200
Cannot render console from 192.168.2.144! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by OwnersController#index as HTML
Parameters: {"name"=>"hans", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}
Owner Load (0.1ms) SELECT "owners".* FROM "owners" WHERE "owners"."id" = ? LIMIT 1 [["id", 2]]
Owner Load (0.1ms) SELECT "owners".* FROM "owners"
Rendered owners/index.html.erb within layouts/application (1.8ms)
Completed 200 OK in 60ms (Views: 58.9ms | ActiveRecord: 0.2ms)
It's telling 200 ok but nothing happens in the DB.
from Paw-Request (so i can use post. btw. how do i use post in browser request?
Started POST
"/owners?name=hans&password=[FILTERED]&password_confirmation=[FILTERED]"
for 192.168.2.144 at 2015-10-01 12:12:45 +0200 Cannot render console
from 192.168.2.144! Allowed networks: 127.0.0.1, ::1,
127.0.0.0/127.255.255.255 Processing by OwnersController#create as HTML Parameters: {"name"=>"hans", "password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]"} Can't verify CSRF token
authenticity Redirected to http://192.168.2.144:3000/ Filter chain
halted as :authenticate_user rendered or redirected Completed 302
Found in 1ms (ActiveRecord: 0.0ms)
It seems that the CRSF authentication failed..
Edit:
at first:
to Rich Peck! This helped me so much. Thank you!! I really appreciate your effort.
Im near to the solution.. My problem is: i cant put the correct params in the url. The token-auth is disabled for testing. so it wont matter.
the params should be like:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"q9JvFhoSUgfydFTvh18JHbIIdKNDjnOS9m/trVBu9EHPP04xGsO69zPh1BFZBI1Ev1YcnOTiPmaAiPWOSkm5Xg==", "owner"=>{"name"=>"Hubert", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create Owner"}
and not as in my request:
Parameters: {"name"=>"Hubert", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "owner"=>{}}
HTTP Status Codes
Firstly, a 30x response means "Resource Moved".
301 responses are used by many SEO people to denote permanent relocation of resources. 302 not so common, but still means a similar thing.
Every time you send & receive HTTP requests, you're going to receive a status code. The typical is the 200 response -- status success!
What you're seeing is the redirect_to command in action -
if #owner.save!
flash[:notice] = ...
redirect_to owners_path
I've never used PAW before, but I assume it's just giving you the pure response of the server, which would in this case be a 30x "Resource Moved" code.
I would expect a typical browser request to load the redirected route and display its yield on the screen.
Server
As a way to test this, you should attempt the same transaction in your browser:
lvh.me:3000/orders
(lvh.me is a domain routed to your own localhost which helps with subdomains in Rails)
This will give you the ability to test and see what happens with the responses. You *should * find that your data has been saved to the database (albeit SQLite3 in your case).
Syntax
Finally, you need to ensure you're using the correct syntax in your code.
Specifically:
#app/controllers/owners_controller.rb
class OwnersController < ApplicationController
...
def create
#owner = Owner.new owner_params
end
private
def owner_params
params.require(:owner).permit(:name, :password, :password_confirmation)
end
end
You'll also want to look at bcrypt-ruby for protecting your passwords.
Testing
I tend to just test my Rails apps with standard browser functionality.
This means you can run the Rails Server ($ rails s in your console), which you'll then be able to then access through your browser.
You're trying to use this PAW thing, which is okay, but doesn't give you much flexibility in regard to the user-interactivity of the app (for example, submitting real forms etc)...
In your case, I'd do the following:
#app/views/orders/new.html.erb
<%= form_for #order do |f| %>
<%= f.text_field :name %>
<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>
<%= f.submit %>
<% end %>
You'd then access lvh.me:3000/orders/new and submit the form. This will show you how it responds!
HTTP
Okay here's the deal with HTTP requests...
Whenever you send a piece of transactional data to your web application, you do it through an HTTP request. HTTP requests are just a way to send data through the "Internet".
With Rails based apps, this means that every time you "do" something in the app, you're really sending an HTTP request to your web server. Rails interprets this request and sends a response. This response is what your question is about.
You're asking about receiving 302 responses - this is the web server's way of saying you've been redirected. It's pretty basic stuff to be honest; your browser handles most of it.
A great tutorial can be found here:
Alright then your error is as follows:
Can't verify CSRF token authenticity
I can elaborate more on this later, but for now, you might want to look up this solution: WARNING: Can't verify CSRF token authenticity in case of API development
Related
flash[:notice] gets erased as soon as I use redirect_to in rails 2.2.2
It's a super simple ruby application, so it shouldn't be to hard to find what's going on (although, I couldn't find it obviously...)
My routes.rb looks like this
resources :happenings
root to: "happenings#index"
post "/happenings/save"
And my HappeningsController looks like this
def index
#happenings = Happening.all
end
def save
flash[:notice] = "saved"
redirect_to root_path
end
Now if I'm debugging and I add puts flash[:notice] to the save action, it will print "saved" to my terminal
if I add `puts flash[:notice] to the index action, it will print an empty line to the terminal. So it obviously has been erased by the time the index action gets executed.
Any ideas? Thanks a lot?
Edit, Here's a bit more information.
The save action get's called by a form
<form method="post" action="/happenings/save">
The following is the server's output when I submit a form (and request the save action)
Started POST "/happenings/save" for 127.0.0.1 at 2015-07-02 23:16:31 +0200
Processing by HappeningsController#save as HTML
Parameters: {"happening_name"=>"Test happening", "happening_time"=>"2015-07-24T13:15"}
Can't verify CSRF token authenticity
Redirected to http://localhost:3000/
Completed 302 Found in 1ms (ActiveRecord: 0.0ms)
Started GET "/" for 127.0.0.1 at 2015-07-02 23:16:32 +0200
Processing by HappeningsController#index as HTML
Rendered happenings/index.html.erb within layouts/application (0.1ms)
Completed 200 OK in 32ms (Views: 28.4ms | ActiveRecord: 0.0ms)
https://stackoverflow.com/a/12340941/2011580
If you are having problem to keep the flash after redirecting to another path, then use this.
flash.keep
in your method, before redirecting.
You might want to do something like this:
def save
redirect_to root_path
flash[:notice] = "saved"
end
And then place
<%= flash[:notice] %>
anywhere in your index.html.erb.
Can you make sure you aren't reseting any cookie from application controller? Because flash messages are stored in cookie. You can also try
flash.now[:notice] = '....'
before redirection you can use:
flash.keep(:notice)
source: http://guides.rubyonrails.org/action_controller_overview.html
A tip:
You can install a gem named pry. You can set that in your view file
when you need, so you can get an interactive shell in your server when
the server serve that page. There you can test all your dynamic value
carriers. And you can understand whats going on actually.
I'm running into a perplexing issue that I can only resolve partway, and hopefully, someone more experienced can tell me whether I can achieve what I wish, or if I'm barking up the wrong tree.
I have a Rails 4 application which uses Devise and CanCan. I'd like to make a small subset of application functionality available to guest users (not logged in). I can achieve this by specifying a get route to a controller method and using link_to to reach that method. I cannot, however, figure out how to get the value of a select box to pass along as parameters on that page without making that view a form using form_tag (there is no model associated with this view).
I can pass hardcoded params along like so:
<%= link_to "Month", activities_search_month_path(:resource_id => 4) %>
but I'd rather have something like:
<%= link_to "Month", activities_search_month_path(:foo => :resource_id) %>
where the second symbol refers to the value of a select_tag. This second example delivers a literal value of "resource_id" when I dump the :foo key unless I convert my view to a form.
If I turn the view into a form by enclosing all the erb in a form_tag, I get a 401 Forbidden error, after which the Devise sign in form is rendered. My guess is that any time you want to process a form, Rails (or Devise) demands authentication on some level. The behavior is the same when I use button_to rather than link_to, since button_to wraps itself in a form under the covers.
How can I set that resource_id argument in my link_to, or will I be forced to create a guest user access level and silently log in guest users? It's important for the UX that users can access this functionality with the least amount of effort possible.
Thanks in advance.
Addendum: quick_search method from controller
def quick_search
puts "quick search 0"
if(params[:time_period] == 'today')
#resource = Resource.find(params[:resource_id])
#site = Site.find(params[:site_id])
#time_period_string = "Activities for #{localize_date(Date.today)} at #{#resource.name}, #{#site.name}"
puts "quick search 1"
if user_signed_in?
puts "quick search 2a"
#activities = Activity.where("system_id = ? and start_date = ? and activity_status_id = ? and resource_id = ?", current_system_id, #today, 2, params[:resource_id])
else
puts "quick search 2b"
if(Setting["#{current_subdomain_not_signed_in}.quick_search_guest_access"] == 'true')
puts "quick search 3a"
current_system_id = current_system_id_not_signed_in
#activities = Activity.where("system_id = ? and start_date = ? and activity_status_id = ? and resource_id = ?", current_system_id, #today, 2, params[:resource_id])
else
puts "quick search 3b"
redirect_to '/users/sign_in'
end
end
end
Note: the quick_search method is never entered. CanCan (or maybe Devise) steps in immediately and redirects to sign in:
Console output:
Started GET "/activities/quick_search" for 127.0.0.1 at 2015-04-12 18:01:58 -0700
Processing by ActivitiesController#quick_search as HTML
(0.2ms) SELECT DISTINCT "systems"."subdomain" FROM "systems"
Completed 401 Unauthorized in 1ms
Started GET "/users/sign_in" for 127.0.0.1 at 2015-04-12 18:01:58 -0700
Processing by Devise::SessionsController#new as HTML
(0.2ms) SELECT DISTINCT "systems"."subdomain" FROM "systems"
Rendered layouts/_header.html.erb (0.8ms)
Rendered devise/shared/_links.html.erb (4.1ms)
Rendered devise/sessions/new.html.erb within layouts/application (14.7ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 285ms (Views: 282.3ms | ActiveRecord: 0.2ms)
Ability.rb
can :quick_search, Activity
can :search_day, Activity
can :search_week, Activity
can :search_month, Activity
The odd thing is that link_to quick_search fails with a 401, but link_to the other three methods works fine -- I just can't get parameters to them dynamically.
If you are using CanCan(Can?) you can define a special ability for guests.
How does your Ability-model look?
Which controller are handling the action that you want to view?
How do you authenticate with CanCan in this controller?
https://github.com/CanCanCommunity/cancancan/wiki/CanCan-2.0
Under the "Defining Abilities" you can see a non-user example.
Fixing CanCan is probably the best option, if you do not want to:
For the part with the link and select box it would be easiest to handle as a form and then handle the redirect in the controller, it could also be done with a remote ajax form.
http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html
This should work:
<% form_tag Activity, activity_quick_search_path, remote: true do %>
<%= select_tag :resource_id...%>
<%= submit_tag %>
<%end%>
Edit after comments:
The culprit here is(was) an:
before_action :authenticate_user!
Causing Devise to redirect to sign in page.
However, if you have CanCan you shouldn't need the authenticate_user.
Short example:
With only Devise I would do:
class NewsController < ApplicationController
before_action :authenticate_user!
before_action :set_news, except: [ :index, :new ]
def index
#news = News.all
end
def show
end
def new
#news = News.new
end
def edit
end
def create
#news = News.new(news_params)
flash[:notice] = 'News created' if #news.save!
redirect_to #news
end
def update
#news.update! news_params
redirect_to #news
end
def destroy
#news.destroy!
redirect_to News
end
private
def news_params
params.require(:news).permit(some_attributes)
end
def set_news
#news = News.find(params[:id])
end
end
How it looks with CanCanCan:
class NewsController < ApplicationController
load_and_authorize_resource
def index
end
def show
end
def new
end
def edit
end
def create
flash[:notice] = 'News created' if #news.save!
redirect_to #news
end
def update
#news.update! news_params
redirect_to #news
end
def destroy
#news.destroy!
redirect_to News
end
private
def news_params
params.require(:news).permit(some_attributes)
end
end
Which I find super neat 😄
Hope that this can help as well.
I've implemented Matteo Melanis great blog article A Simple Token Authentication Service for Mobile Devices. It works beautifully with the Chrome extension Postman. However, when I try to fetch a user authentication token with cUrl, I'm running into a bizzare problem.
First the development.log entry for the (successful) authentication fetch using Postman:
Started POST "/api/v1/tokens.json?email=my#mail.com&password=[FILTERED]" for 127.0.0.1 at 2013-11-25 11:28:21 +0100
Processing by Api::V1::TokensController#create as JSON
Parameters: {"email"=>"my#mail.com", "password"=>"[FILTERED]"}
[1m[36mUser Load (1.4ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1[0m
Entered create method
[1m[35mUser Load (3.9ms)[0m SELECT "users".* FROM "users" WHERE "users"."email" = 'my#mail.com' LIMIT 1
Completed 200 OK in 99ms (Views: 0.3ms | ActiveRecord: 5.3ms)
Then, when I run $ curl -X POST "https://localhost:3000/api/v1/tokens.json?email=my#mail.com&password=somepassword" -d "email=my#mail.com&password=somepassword" -v -k -i, I get
Started POST "/api/v1/tokens.json?email=my#mail.com&password=[FILTERED]" for 127.0.0.1 at 2013-11-25 11:29:01 +0100
Processing by Api::V1::TokensController#create as JSON
Parameters: {"email"=>"my#mail.com", "password"=>"[FILTERED]"}
Completed 401 Unauthorized in 12ms
You might ask why I provided the parameters both as HTTP Post data, and as a query string. Well, my initial research with the curl lib sample http-post.c suggest the former, while Postmans successful query suggests the latter. I've tried all combinations of these, but nothing works, so I'm pretty lost.
In the Api::V1::TokensController, I've added logging whenever the create method is being called, that is
class Api::V1::TokensController < ApplicationController
skip_before_filter :verify_authenticity_token
respond_to :json
def create
Rails.logger.debug("Entered create method")
email = params[:email]
password = params[:password]
if request.format != :json
render :status=>406, :json=>{:message=>"The request must be json"}
return
end
if email.nil? or password.nil?
render :status=>400,
:json=>{:message=>"The request must contain the user email and password."}
return
end
#user=User.find_by_email(email.downcase)
if #user.nil?
logger.info("User #{email} failed signin, user cannot be found.")
render :status=>401, :json=>{:message=>"Invalid email or password."}
return
end
# http://rdoc.info/github/plataformatec/devise/master/Devise/Models/TokenAuthenticatable
#user.ensure_authentication_token!
if not #user.valid_password?(password)
logger.info("User #{email} failed signin, password \"#{password}\" is invalid")
render :status=>401, :json=>{:message=>"Invalid email or password."}
else
render :status=>200, :json=>{:token=>#user.authentication_token}
end
end
def destroy
#user=User.find_by_authentication_token(params[:id])
if #user.nil?
logger.info("Token not found.")
render :status=>404, :json=>{:message=>"Invalid token."}
else
#user.reset_authentication_token!
render :status=>200, :json=>{:token=>params[:id]}
end
end
end
As can be seen from the logs, create method is being called in the first place, but not in the second. It is as if Api::V1::TokensController's skip_before_filter :verify_authenticity_token is ignored altogether. But how can that be?
Any suggestion is greatly appreciated!
So here's what I did. For the regular html views, I'd like to keep using cookies for user convenience. For the (mobile) REST API, I'd like to disable cookies, as auth_token will be used throughout.
I'm not a Rails/Devise super hero, so I'm a little shaky about this, but I think it should be ok ... anyway: I disabled authentication before hitting the tokens controller altogether. In order to get anything sensible out of the tokens controller, you'd have to supply a matching email/password credentials pair anyway, so I can't (at the moment) see any obvious security vulnerabilities with this approach.
Thus, my new TokensController look like this:
class Api::V1::TokensController < ApplicationController
skip_before_filter :verify_authenticity_token
skip_before_filter :authenticate_player!
respond_to :json
def create
# ....
Hope this helps someone else stuck out there. And any feedback on possible security issues is greatly appreciated!
Update:
I forgot to mention that, as of now, the entire application is communicated over HTTPS.
I've got a very simple app where the flow looks like this:
User reads some copy, decides they want to purchase the product and fill out the form, see confirmation page.
Something is wrong in my controller but I can't quite pinpoint it where I'm getting the error Couldn't find Customer without an ID.
class CustomersController < ApplicationController
# before_filter :load_customer, :only => :show
def new
#customer = Customer.new
end
def create
#customer = Customer.new(params[:customer])
if #customer.save
session[:customer_id] = #customer.id
purchase
else
flash[:error] = "Please enter a valid email address"
redirect_to :signup
end
end
def signup
#customer = Customer.new
end
def purchase
Stripe.api_key = STRIPE['secret']
charge = Stripe::Charge.create(
:amount => 2000,
:currency => "usd",
:card => params[:stripe_token],
:description => "My Product Name"
)
redirect_to receipt_path
end
def receipt
#customer = Customer.find(session[:customer_id])
#name = #customer.name
#email = #customer.email
#product = #customer.product
end
# private
#
# def load_customer
# #customer = Customer.find(session[:customer_id])
# redirect_to request.path.gsub(params[:id], session[:customer_id].to_s) if params[:id] != session[:customer_id].to_s
# end
end
I'm not sure where things are screwing up and after much Googling, I'm turning to you guys. Help would be huge.
EDIT:
Consulting with Rails console shows that my application isn't making new customer records for some reason. Charging is working, however. Customers not being created must be a precursor to this.
EDIT 2: Development.log
Started GET "/assets/bootstrap.js?body=1" for 127.0.0.1 at 2012-08-28 15:58:11 -0700
Served asset /bootstrap.js - 304 Not Modified (0ms)
[2012-08-28 15:58:11] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
Started POST "/checkout" for 127.0.0.1 at 2012-08-28 15:58:12 -0700
Processing by CustomersController#purchase as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"k2aW/CAkNfwDSMHHvzbuOwm+Xua0qb2LJ4LtrtRvyvk=", "customer"=>{"name"=>"Your name", "email"=>"yourname#example.com"}, "stripe_token"=>"tok_0GUvwKPwo6jfEu"}
Redirected to http://localhost:3000/receipt
Completed 302 Found in 1064ms (ActiveRecord: 0.0ms)
Started GET "/receipt" for 127.0.0.1 at 2012-08-28 15:58:14 -0700
Processing by CustomersController#receipt as HTML
Completed 500 Internal Server Error in 0ms
ActiveRecord::RecordNotFound (Couldn't find Customer without an ID):
app/controllers/customers_controller.rb:38:in `receipt'
Rendered /Users/zack/.rvm/gems/ruby-1.9.3-p194#beat-the-herd/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (3.9ms)
Rendered /Users/zack/.rvm/gems/ruby-1.9.3-p194#beat-the-herd/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (5.6ms)
Rendered /Users/zack/.rvm/gems/ruby-1.9.3-p194#beat-the-herd/gems/actionpack-3.2.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (23.7ms)
If the user routes directly to receipt action then session[:customer_id] may be nil. That's why you get the error. This is not happened if a create (possibly) POST request is issued. In this case, the session variable has been populated before the redirection to the receipt action.
This line :
#customer = Customer.find(session[:customer_id])
throws an error because session[:customer_id] is nil
You might want to use find_by_id that won't throw an Exception but will return an nil record.
Then you'll have to deal with the case of #customer being nil.
Add this in UserController
def show <br>
#user = User.find(session[:user_id])<br>
#profile = #user.profile<br>
end
Rather than putting "user_id" put session[:user_id]
It worked for me
Can someone help me understand how to make Ryan Bate's screencast on Backbone.js work with MongoDB as my database while using the Mongoid gem.
This is what I am seeing.
When I create a new entry via the console, similar to how Ryan did it in the video with entry.create, Rails adds that entry just fine. Below is my Ruby log and my JavaScript headers log from Chrome Inspector.
Ruby Log
Started POST "/api/entries" for 127.0.0.1 at 2012-02-12 17:31:24 -0600
Processing by EntriesController#create as JSON
Parameters: {"name"=>"Heather", "entry"=>{"name"=>"Heather", "action"=>"create", "controller"=>"entries"}}
MONGODB w_market_development['system.namespaces'].find({})
MONGODB w_market_development['entries'].insert([{"_id"=>BSON::ObjectId('4f384bcc504b9348be000003'), "name"=>"Heather"}])
Completed 201 Created in 11ms (Views: 2.4ms)
Headers Log
Request URL:http://0.0.0.0:3000/api/entries
Request Method:POST
Status Code:201 Created
Request Headers (14)
Request Payload
{"name":"Heather"}
As you can see it posted fine. Now let me show you an update via the entry.save() example Ryan showed us.
Ruby Log
Started POST "/api/entries" for 127.0.0.1 at 2012-02-12 17:34:25 -0600
Processing by EntriesController#create as JSON
Parameters: {"_id"=>"4f38152c504b9345dc000005", "name"=>"Bloip", "winner"=>true, "entry"=>{"_id"=>"4f38152c504b9345dc000005", "name"=>"Bloip", "winner"=>true, "action"=>"create", "controller"=>"entries"}}
MONGODB w_market_development['system.namespaces'].find({})
MONGODB w_market_development['entries'].insert([{"_id"=>BSON::ObjectId('4f38152c504b9345dc000005'), "name"=>"Bloip", "winner"=>true}])
Completed 201 Created in 12ms (Views: 2.7ms)
Headers Log
Request URL:http://0.0.0.0:3000/api/entries
Request Method:POST
Status Code:201 Created
Request Headers (14)
Request Payload
{"_id":"4f38152c504b9345dc000005","name":"Bloip","winner":true}
As you can see when I complete the entry.save() on a current entry, which should be an update, the JSON is showing a POST instead of a PUT, which Mongoid is doing nothing with and the DB shows no changes. After Googling I found the following articles but nothing really helped.
https://github.com/codebrew/backbone-rails/issues/8
http://lostechies.com/derickbailey/2011/06/17/making-mongoid-play-nice-with-backbone-js/
When I was going through the RailsCast as described above. I was using the entries controller that Ryan put together. After much searching, copying, pasting, and retrying I found that I need a completely new Controller set up. Below is what I originally had.
class EntriesController < ApplicationController
respond_to :json
def index
respond_with Entry.all
end
def show
respond_with Entry.find(params[:id])
end
def create
respond_with Entry.create(params[:entry])
end
def update
respond_with Entry.update(params[:id], params[:entry])
end
def destroy
respond_with Entry.destroy(params[:id])
end
end
This is the Controller code the fixed the issue for me.
class EntriesController < ApplicationController
def index
render :json => Entry.all
end
def show
render :json => Entry.find(params[:id])
end
def create
entry = Entry.create! params
render :json => entry
end
def update
entry = Entry.find(params[:id])
entry.update_attributes!(params[:entry])
render :json => entry
end
def destroy
render :json => Entry.destroy(params[:id])
end
end
Thanks All!
Travis