Padrino model from json data
Yep, you can use provides
and each response object will call to_json
i.e:
get :action, :provides => :json do
@colletion = MyCollection.all
render @collection # will call @collection.to_json
end
Here an example of an ugly code that fills certain models.
# Gemfile
gem 'json' # note that there are better and faster gems like yajl
# controller
post "/update/:model/:id", :provides => :json do
if %w(Account Post Category).include?(params[:model])
klass = params[:model].constantize
klass.find(params[:id])
klass.update_attributes(JSON.parse(params[:attributes]))
end
end
Finally if you POST a request like:
attributes = { :name => "Foo", :category_id => 2 }.to_json
http://localhost:3000/Account/12?attributes=#{attributes}
You'll be able to update record 12 of the Account Model.
Storing json object in Padrino CouchDB model
It's not necessary to stringify json, just parse it and store as an array using the JSON standard lib.
original JSON data example:
json_data = [{ prop1: val1, prop2: val2, prop3: val3 }] #store the JSON data from wherever it came
parsed = JSON.parse(json_data.to_json) #store the parsed JSON data into an Array
foo = MyModel.find(1) #find whatever collection you wanna update
foo.properties = parsed
# => [{ prop1: val1, prop2: val2, prop3: val3 }]
foo.save
Your MyModel should then look like the following:
{
"_id" : "your_generated_id",
"_rev" : "your_generated_rev",
"name" : "UniqueName",
"properties" : [
{
prop1: val1,
prop2: val2,
prop3: val3
}
]
}
Remember CouchDB is "schemaless". More details here.
Why is Padrino trying to use a template when rendering a json response?
So I got it to work by replacing render @records, layout: false
with @records.to_json
.
Pretty sure that's not how it's supposed to work, so if anyone knows a better way I'm all ears, otherwise I'll accept this answer.
Padrino app with REST API
Blog::App.controllers :posts, map: '/api/v1/posts' do
get :index do
...
end
end
And then, if you want add new versions of that controller
Blog::App.controllers :v2_posts, map: '/api/v2/posts' do
get :index do
...
end
end
(Yeah, it seems you can't have several files with the same controller with different map
values.)
So, this won't work (sorry if that works, that doesn't when I tried) correctly and will cause issues :
Blog::App.controllers :posts, map: '/api/v1/posts' do
get :index do
...
end
end
Blog::App.controllers :posts, map: '/api/v2/posts' do
get :index do
...
end
end
How can I clean up this Padrino AJAX call?
first of all, you should protect your model from mass assignments using attr_accessible and attr_protected aka mass assignment.
Then I highly suggest to use "forms" so your site can work without javascript enabled.
So using unobtrusive javascripts code can be also nicer.
// Live watch events on form submit
$(document).on('submit', 'form[data-remote]', function(e){
e.preventDefault();
self = $(this);
$.ajax({
url: self.attr('action'),
data: self.serializeArray(),
type: self.attr('method'),
dataType: 'json',
success: function(res){ console.log(res) }
})
});
Here the form:
/* Here the form, for dates I suggest to use a calendar */
/* like https://github.com/arshaw/fullcalendar */
- form_for @trip, url(:trip, :index), :'data-remote' => true do |f|
== f.error_messages
== f.text_field :title
== f.text_area :description
== f.text_field :departure_date
== f.text_field :return_data
== f.submit 'Send'
Here the controller:
provides :json # if all your actions in your controller respond to #json it is more dry
get :index do
@trip = Trip.new(params[:trip])
if @trip.save
render :success => true, :attributes => @trip.to_json
else
render :success => false, :errors => @trip.errors.full_messages
end
end
LoadError on Windows when trying to generate a model
Put sqlite3.dll
to C:\Ruby193\bin
Related Topics
Product Orders Between 2 Users
How to Execute 2 or More Commands in the Same Ssh Session
Why Does Hash#Select and Hash#Reject Pass a Key to a Unary Block
How to Add Conditional Rubygem Requirements to a Gem Specification
Include Erb Delimiters Inside of a String in an Erb Block
Ruby Converting Utc to User's Time Zone
Rails Gem to Break a Paragraph into Series of Sentences
Triple Single Quote VS Triple Double Quote in Ruby
Get Pry to Display Characters Like [äöüßÄÖÜß] (Utf-8 Encoding)? (Possibly Windows-Specific Issue)
Why Is My Ruby Git Script Hook Run with the Wrong $Path
Best Way to Find_Or_Create_By_Id But Update the Attributes If the Record Is Found
How to Set Up the Recipient Id in Public Activity
Include Erb Delimiters Inside of a String in an Erb Block
How to Capture a Part of a Screen Using Ruby on Windows
Rmagick Error After Installing Os X Mavericks
Having Difficulty Accessing Validation Errors in Sinatra
Running Selenium::Webdriver::Firefox Inside Xvfb from Ruby as Non-Root User