I have a Rails application with articles and users.
So i want that a user can login out from an client application with json object and get all the article also with a json object.
But, I have some problems. Console output:
Started POST "/articles" for 127.0.0.1 at 2012-03-30 17:29:25 +0200
Processing by ArticlesController#create as JSON
Parameters: {"id"=>1, "article"=>{"id"=>1}}
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 1ms
And here the Controler:
class ArticlesController < ApplicationController
before_filter :authenticate_user!, :except => [:show, :index]
# GET /articles
# GET /articles.json
def index
#articles = Article.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #articles }
end
end
# GET /articles/1
# GET /articles/1.json
def show
#article = Article.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #article }
end
end
# GET /articles/new
# GET /articles/new.json
def new
#article = Article.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #article }
end
end
# GET /articles/1/edit
def edit
#article = Article.find(params[:id])
end
# POST /articles
# POST /articles.json
def create
#article = Article.new(params[:article])
respond_to do |format|
if #article.save
format.html { redirect_to #article, notice: 'Article was successfully created.' }
format.json { render json: #article, status: :created, location: #article }
else
format.html { render action: "new" }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
# PUT /articles/1
# PUT /articles/1.json
def update
#article = Article.find(params[:id])
respond_to do |format|
if #article.update_attributes(params[:article])
format.html { redirect_to #article, notice: 'Article was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
# DELETE /articles/1
# DELETE /articles/1.json
def destroy
#article = Article.find(params[:id])
#article.destroy
respond_to do |format|
format.html { redirect_to articles_url }
format.json { head :no_content }
end
end
end
And the Model:
class Article < ActiveRecord::Base
end
The JSON that I send looks like this:
{
"id" : 1
}
Routes
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root / articles#index
Now my quesiton: is my JSON object wrong or am I missing something, like the CSRF token?
You need to make sure the CSRF token is submitted with each JSON HTTP Request. This is how I do it:
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
});
Related
I have a method in my rails controller and in the controller I need to render the output as a message in json format.
def createItem
#item = Item.new(params[:item])
respond_to do |format|
if #item.save
format.json { render json: message: "Item is successfully Created" }
else
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
But when I submit the form, the browser is displaying blank. I need to render the json text as above. How do I do it. Please help
You could change,
def createItem
#item = Item.new(params[:item])
respond_to do |format|
if #item.save
format.json { render json: message: "Item is successfully Created" }
else
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
To
def createItem
#item = Item.new(params[:item])
respond_to do |format|
if #item.save
json_string = {'message' => 'Item is successfully Created'}.to_json
format.json { render :json => {item: #item, json_string}
else
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
If you want to see the JSON request you should have to give the .json at the end of your URL.
Suppose that you dont want to give the url, in your model you should type :
def as_json(options={})
{ :name => self.name } # NOT including the email field
end
def as_json(options={})
super(:only => [:name])
end
And then in your controller :
def index
#names = render :json => Name.all
end
Then the JSON code will automatically come to picture without using .json.
I am using Gmaps4rails API. But whenever I update or edit the address, gmaps4rails still points to the old address. I am new to rails, so am not sure what is the mistake.
Below is my Controller.rb file
def show
if current_user.Company.nil?
#estate = current_user.estates.find(params[:id])
else
#estate = Estate.find(params[:id])
end
respond_to do |format|
format.html # show.html.erb
format.json { render json: #estate }
end
end
def new
##key = params[:user_id]
#master = ##key
#estate = Estate.new
#json = #estate.all.to_gmaps4rails
respond_to do |format|
format.html # new.html.erb
format.json { render json: #estate }
end
end
def edit
#estate = Estate.find(params[:id])
#json = #estate.to_gmaps4rails
end
def create
# #estate = Estate.new(params[:estate])
if current_user.Company.nil?
#estate = current_user.estates.build(params[:estate])
else
serve = User.find(##key)
#estate = Estate.new(params[:estate])
#estate.user_id = serve.id
#estate.Mgmt = current_user.Company
end
respond_to do |format|
if #estate.save
if current_user.Company.nil?
if #estate.companyemail = ''
##
else
EstateMailer.company_confirmation(#estate).deliver
end
end
format.html { redirect_to #estate, notice: 'Property details were successfully updated.' }
format.json { render json: #estate, status: :created, location: #estate }
else
format.html { render action: "new" }
format.json { render json: #estate.errors, status: :unprocessable_entity }
end
end
end
def update
#estate = Estate.find(params[:id])
#json = Estate.all.to_gmaps4rails
respond_to do |format|
if #estate.update_attributes(params[:estate])
format.html { redirect_to #estate, notice: 'Property details were successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #estate.errors, status: :unprocessable_entity }
end
end
end
Try this as per SO post
You'll need something like this in your model
:check_process : true/false (if set to false, geocoding will be made at every save/update)
:checker : string (only if check_process is true), could be a method or a db column boolean
More info here. Remember, Google is your friend.
after upgrading to rails 3.2.8 my private methods that passes mass assignment in rails 3.2.6 no longer passes i keep getting the mass assignment error.
my controller is
class AddressesController < BaseController
# GET /addresses
# GET /addresses.json
def index
#address = Address.new
form_info
respond_to do |format|
format.html # index.html.erb
format.json { render json: #addresses }
end
end
# GET /addresses/1
# GET /addresses/1.json
def show
#address = Address.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #address }
end
end
# GET /addresses/new
# GET /addresses/new.json
def new
#address = Address.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #address }
end
end
# GET /addresses/1/edit
def edit
#address = Address.find(params[:id])
end
# POST /addresses
# POST /addresses.json
def create
if params[:address].present?
#address = current_user.addresses.new(params[:address])
#address.default = true if current_user.default_shipping_address.nil?
#address.save_default_address(current_user, params[:address])
elsif params[:address_id].present?
#address = current_user.addresses.find(params[:address_id])
end
respond_to do |format|
if #address.id
update_order_address_id(#address.id)
format.html { redirect_to(orders_url, :notice => 'Address was successfully created.') }
else
form_info
format.html { render :action => "index" }
end
end
end
# PUT /addresses/1
# PUT /addresses/1.json
def update
#address = Address.find(params[:id])
respond_to do |format|
if #address.update_attributes(params[:address])
format.html { redirect_to #address, notice: 'Address was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #address.errors, status: :unprocessable_entity }
end
end
end
# DELETE /addresses/1
# DELETE /addresses/1.json
def destroy
#address = Address.find(params[:id])
#address.destroy
respond_to do |format|
format.html { redirect_to addresses_url }
format.json { head :no_content }
end
end
private
def update_order_address_id(id)
session_order.update_attributes(
:address_id => id
)
end
def form_info
#addresses = current_user.addresses
end
end
after creating an address i expect it to perform update_order_address_id(id) method but it keeps telling me
Can't mass-assign protected attributes: address_id
All this started after upgrading to rails 3.2.8. Does any body know how i can fix this please or any suggestions towards this.
Try to add this line to the model
attr_accessible :address_id
https://stackoverflow.com/a/4538861/643500
Edit:
Not sure if you read this
class AccountsController < ApplicationController
include ActiveModel::MassAssignmentSecurity
attr_accessible :first_name, :last_name
attr_accessible :first_name, :last_name, :plan_id, :as => :admin
def update
...
#account.update_attributes(account_params)
...
end
protected
def account_params
role = admin ? :admin : :default
sanitize_for_mass_assignment(params[:account], role)
end
end
http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html
I need a search form in my rails 3.2.3 application, but i don't know how to do this, yesterday i had it fixed but then i deleted it :(.
Here are my Controller and Model:
Controller
class BedrijfsgegevensController < ApplicationController
def index
#bedrijfsgegevens = Bedrijfsgegeven.all
#bedrijfsgegevens = Bedrijfsgegeven.search(params[:search])
respond_to do |format|
format.html # index.html.erb
format.json { render json: #bedrijfsgegevens }
end
end
# GET /bedrijfsgegevens/1
# GET /bedrijfsgegevens/1.json
def show
#bedrijfsgegeven = Bedrijfsgegeven.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #bedrijfsgegeven }
end
end
# GET /bedrijfsgegevens/new
# GET /bedrijfsgegevens/new.json
def new
#bedrijfsgegeven = Bedrijfsgegeven.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #bedrijfsgegeven }
end
end
# GET /bedrijfsgegevens/1/edit
def edit
#bedrijfsgegeven = Bedrijfsgegeven.find(params[:id])
end
# POST /bedrijfsgegevens
# POST /bedrijfsgegevens.json
def create
#bedrijfsgegeven = Bedrijfsgegeven.new(params[:bedrijfsgegeven])
respond_to do |format|
if #bedrijfsgegeven.save
format.html { redirect_to #bedrijfsgegeven, notice: 'Bedrijfsgegeven was successfully created.' }
format.json { render json: #bedrijfsgegeven, status: :created, location: #bedrijfsgegeven }
else
format.html { render action: "new" }
format.json { render json: #bedrijfsgegeven.errors, status: :unprocessable_entity }
end
end
end
# PUT /bedrijfsgegevens/1
# PUT /bedrijfsgegevens/1.json
def update
#bedrijfsgegeven = Bedrijfsgegeven.find(params[:id])
respond_to do |format|
if #bedrijfsgegeven.update_attributes(params[:bedrijfsgegeven])
format.html { redirect_to #bedrijfsgegeven, notice: 'Bedrijfsgegeven was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #bedrijfsgegeven.errors, status: :unprocessable_entity }
end
end
end
# DELETE /bedrijfsgegevens/1
# DELETE /bedrijfsgegevens/1.json
def destroy
#bedrijfsgegeven = Bedrijfsgegeven.find(params[:id])
#bedrijfsgegeven.destroy
respond_to do |format|
format.html { redirect_to bedrijfsgegevens_url }
format.json { head :no_content }
end
end
end
Model
class Bedrijfsgegeven < ActiveRecord::Base
def search
#search = Bedrijfsgegeven.search() do
keywords(params[:search])
end
end
def self.search(search)
if search
find(:all, :conditions => ['Voornaam LIKE ?', "%#{search}%"])
else
find(:all)
end
end
validates :voornaam,
:achternaam,
:woonplaats,
:telefoon,
:website,
:email,
:presence => true
attr_accessible :achternaam, :email, :telefoon, :voornaam, :website, :woonplaats
end
i hope someone could help me out with this.
Grtz Kees
Have you read / watched the following railscast:
http://asciicasts.com/episodes/240-search-sort-paginate-with-ajax
Helps me every time I need basic search
I will recommend you to start using repositories which will make you safe from these incidental delete. You can get 5 free repositries at bitbucket.org. Both git and mercurial are awesome.
Am having trouble getting the Atom feed function to work on my blog. I am using the Kaminari plug-in to paginate my articles - 6 per page. With the code below, when a user clicks on the RSS Feed image they are asked to log-in instead of subscribing to the feed! Any help would be appreciated with this issue...
application.html.erb
page head <%= auto_discovery_link_tag(:atom, feed_path, { :title => "My ATOM Feed" }) %>
page body <%= image_tag("feed.png", {:alt => 'Atom feed', :class=>"feed"}) %>Subscribe
routes.rb
match '/feed' => 'articles#feed', :as => :feed, :defaults => { :format => 'atom' }
articles_controller
class ArticlesController < ApplicationController
before_filter :authenticate_user!, :except => [:index, :show]
# GET /articles
# GET /articles.xml
# display articles on the home page
def index
#articles = Article.published.page(params[:page]).per(6).ordered
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #articles }
format.atom { render :atom => #articles }
end
end
# GET /articles/1
# GET /articles/1.xml
def show
#article = Article.find(params[:id])
#comment = Comment.new(:article=>#article)
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #article }
end
end
# GET /articles/new
# GET /articles/new.xml
def new
#article = Article.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #article }
end
end
# GET /articles/1/edit
def edit
#article = Article.find(params[:id])
authorize! :edit, #article
end
# POST /articles
# POST /articles.xml
def create
#authorize! :create, #article
#article = Article.new(params[:article])
#article.user_id = current_user.id
respond_to do |format|
if #article.save
format.html { redirect_to(#article, :notice => 'Worry was successfully created.') }
format.xml { render :xml => #article, :status => :created, :location => #article }
else
format.html { render :action => "new" }
format.xml { render :xml => #article.errors, :status => :unprocessable_entity }
end
end
end
# PUT /articles/1
# PUT /articles/1.xml
def update
#article = Article.find(params[:id])
authorize! :update, #article
respond_to do |format|
if #article.update_attributes(params[:article])
format.html { redirect_to(#article, :notice => 'Worry was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #article.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /articles/1
# DELETE /articles/1.xml
def destroy
#article = Article.find(params[:id])
authorize! :destroy, #article
#article.destroy
respond_to do |format|
format.html { redirect_to(articles_url) }
format.xml { head :ok }
end
end
end
views/articles/feed.atom.builder
atom_feed :language => 'en-US' do |feed|
feed.title "mysite.com"
feed.updated(#articles.blank? ? Time.now : #articles.first.created_at)
#articles.each do |article|
feed.entry article, :published => article.accepted do |entry|
entry.title article.title
entry.author do |author|
author.name article.user.fullname
end
end
end
end
Update this line in your articles_controller:
before_filter :authenticate_user!, :except => [:index, :show]
... with:
before_filter :authenticate_user!, :except => [:index, :show, :feed]
This will prevent the request for authentication.
Two suggestions:
1) Add :url and :root_url to the atom_feed call.
2) Change:
feed.updated #articles.first.created_at
to:
feed.updated(#articles.blank? ? Time.now : #articles.first.created_at)