save json block of code into nested model ruby rails - ruby-on-rails

I get a hash of results from get_connection with koala gem which looks something like this
=> [{"album"=>{"created_time"=>"2011-05-07T23:06:33+0000", "name"=>"Timeline Photos",
"id"=>"10150170707957371"}, "images"=>[{"height"=>1150, "source"=>"https://scontent.xx.fbcdn.net/v/t31.0-8/24173690_10155086191327371_1463889654041392146_o.jpg?oh=8adec503c6066dc20d1be5d71262a03e&oe=5AFEED4A",
"width"=>2048}, {"album"=>{"created_time"=>"2011-05-07T23:06:33+0000", "name"=>"Timeline Photos",
"id"=>"10150170707957371"}, "images"=>[{"height"=>1188, "source"=>"https://scontent.xx.fbcdn.net/v/t31.0-8/24302317_10155086179077371_4000719398736973936_o.jpg?oh=6eba399a4067b847cb38ef245e687321&oe=5AFC195A",
"width"=>2639}]}]
I was looking to save photos like rails does with the params hash but realized it only creates a gallery for each photo with a do block .
def photos(user)
photos = user.facebook.get_connection("me", "photos?fields=album,images,event,height,width,link,place&type=uploaded")
photos.each do |photo|
params = { gallery: {
name: 'Facebook Pictures', pictures_attributes: [
{ fb_album_created_time: photo['album']['created_time'],
fb_album_name: photo['album']['name'],
fb_album_id: photo['album']['id'],
fb_source: photo['images'][0]['source'],
fb_height: photo['images'][0]['height'],
fb_width: photo['images'][0]['width'],
fb_link: photo['link'],
fb_pic_id: photo['id'] }
]
}
}
gallery = user.galleries.new(params[:gallery])
gallery.save!
end
end
How can I execute my nested picture attributes so they save to one gallery. Even a gem which could help me. I was looking at the rails/jbuider gem but not sure if its easier without a gem?

Fixed this with Jbuilder.
def to_jbuilder
Jbuilder.new
end
def photos(u)
json = to_jbuilder
first_page_photos = u.facebook.get_connection("me", "photos?fields=album,images,event,height,width,link,place&type=uploaded")
photos = json.photo first_page_photos do |photo|
json.fb_album_created_time photo['album']['created_time']
json.fb_album_name photo['album']['name']
json.fb_album_id photo['album']['id']
json.fb_source photo['images'][0]['source']
json.fb_height photo['images'][0]['height']
json.fb_width photo['images'][0]['width']
json.fb_link photo['link']
json.fb_pic_id photo['id']
end
params = { gallery: { name: 'Facebook Pictures', pictures_attributes: photos }}
gallery = u.galleries.new(params[:gallery])
gallery.save!
end

Related

Ruby On Rails: Make controller smaller

So, I have this controller, it gets the data from the uploaded file and save it to the right models. I made it work, but it is gigantic. I would like some directions of how to make it smaller. Should I create a class to extract the data and save to the db?
class UploadsController < ApplicationController
require 'csv'
def save_info_to_db
file = params[:file]
purchases_made = []
CSV.open(file.path, "r", { col_sep: "\t", headers: true }).each do |row|
data = Hash.new
data = {
purchaser: { name: row[0] },
item: { description: row[1], price: row[2], quantity: row[3] },
merchant: { name: row[4], address: row[5] }
}
merchant = Merchant.create_with(address: data[:merchant_address]).find_or_create_by(name: data[:merchant][:name])
item = merchant.items.create_with(price: data[:item][:price]).find_or_create_by(description: data[:item][:description])
purchaser = Purchaser.create(name: data[:purchaser][:name])
purchase = purchaser.purchases.create
purchase_items = PurchaseItem.create(item_id: item.id, quantity: data[:item][:quantity])
purchase.add_purchase_items(purchase_items)
purchases_made << purchase.total_price
end
session[:total_gross_income] = Purchase.total_gross_income(purchases_made)
redirect_to display_incomes_path
end
end
Thank you!
Lots of ways to do this, depending on what you prefer, but one idea is to use a Service class. In the service, you could handle the file processing.
Your controller would then end up looking something like:
class UploadsController < ApplicationController
require 'csv'
def save_info_to_db
file_service = FileProcessingService.new(file)
file_service.save_info!
session[:total_gross_income] = Purchase.total_gross_income(file_service.purchases_made)
redirect_to display_incomes_path
rescue
# perhaps some rescue logic in the event processing fails
end
All your file processing logic would go in the Service. You could even split that logic up -- logic for getting the data from the file, then separate logic for saving the data.
Lots of options, but the general idea is you can use a service to handle logic that may span multiple models.

Paperclip Unpermitted parameter: image

I am trying to get Paperclip to upload an image to s3 from my festival model on form submit but am receiving the Unpermitted parameter: image. error
I have checked the strong params, the model content validation and read through the paperclip documents with no avail.
I think I have narrowed the problem down to my post request to the DB cannot handle the File object that gets assigned to festival.image, but can't figure out how I would represent this in the post request.
I am capturing the data in rails using react on rails on the front end with Rails as the backend. I was following along with this sample code https://github.com/carlbaron/react-file-upload-demo
I also use React-dropzone to capture the uploaded file and it adds the preview attribute for the image preview.
Been stuck on this for some time now, any help greatly appreciated!
Beginning of the post request printed to console
Processing by FestivalsController#create as JSON
Parameters: {"festival"=>{"fest_name"=>"Test Festival", "image"=>{"preview"=>"blob:http://localhost:5000/76b95cb5-45bf-46a9-ba7b-f5b9ad127521"}}}
| Unpermitted parameter: image
Festival object printed to the console
Post Request to the DB via axios
postFestival(festival) {
let config = {
responseType: 'json',
processData: false,
contentType: false,
headers: ReactOnRails.authenticityHeaders(),
};
let str = JSON.stringify(festival);
console.log("ENTITY IS " + str);
//returns
//ENTITY IS {"fest_name":"Test Festival","image":{"preview":"blob:http://localhost:5000/76b95cb5-45bf-46a9-ba7b-f5b9ad127521"}}
return(
request.post('/festivals/create', {festival}, config)
);
},
Festival.rb
class Festival < ApplicationRecord
has_attached_file :image, default_url: "/assets/ASOT-COVER.png"
validates_attachment :image,
content_type: { content_type: ["image/jpeg", "image/gif", "image/png"] }
end
Festivals Controller
def create
#festival = Festival.create(festival_params)
puts "festival.image =" + #festival.image.inspect
#returns = festival.image =#<Paperclip::Attachment:0x007fc288868bf0 #name=:image, #name_string="image", #instance=#
if #festival.save
puts "Festival SAved = + " + #festival.inspect
#returns the festival object saved to the DB minus the image param
else
respond_to do |format|
format.json { render json: #festival.errors, status: :unprocessable_entity}
puts "ERROR = " + #festival.errors.inspect
end
end
private
def festival_params
params.require(:festival).permit(:fest_name, :fest_organizer, :fest_location,
:fest_date, :fest_url, :fest_venue, :fest_description,
:image)
end
end
As the image parameter in your request is a hash "image"=>{"preview"=>"blob:http://localhost:5000/76b95cb5-45bf-46a9-ba7b-f5b9ad127521"}, you will need to modify your festival_params method like this:
def festival_params
params.require(:festival).permit(:fest_name, :fest_organizer, :fest_location,
:fest_date, :fest_url, :fest_venue, :fest_description,
{ image: :preview })
end
Let me know if it solves the error.

Rails app: I need to build a json object from params inside a loop

I need to build a json object inside a loop using params.
My params look like this...
params[:answers]
returns => {"1"=>"answer1", "2"=>"answer2"}
The keys in this json object are the id's of the survey question.
So I planed to loop through the keys to build the json object like this...
def build_answersheet_json(params[:answers], params[:survey_id])
params[:answers].keys.each do |question_id|
current_question = question_id
current_answer = params[:answers][question_id]
end
end
Since im using "t.json" in my migration to save json to postgres, I wanted to use the extracted question_id and answer to build a json object that looks something like this...
{
survey_id: '1',
answers: {
question: [{
question_id: 1,
answer: 'answer1'
}, {
question_id: 2,
answer: 'answer2'
}]
}
}
Ive been trying to do this using a method that looks somthing like this...
build_answersheet_json(params[:answers], params[:survey_id])
Ive tried JSON.parse() and Ive tried to just logically work through it but I cant seem to figure this out.
Any help is appreciated.
Maybe you can try something like that:
/* fake params (to test) */
params = {
survey_id: '1',
answers: {
"1"=>"answer1",
"2"=>"answer2",
"3"=>"answer3",
"4"=>"answer4"
}
}
def build_answersheet_json(answers, survey_id)
{
survey_id: survey_id,
answers: answers.map { |k,v| { question_id: k.to_i, answer: v } }
}
end
survey = build_answersheet_json(params[:answers], params[:survey_id])
puts survey.class
#Hash
puts survey.to_json
# formated JSON string:
# {
# "survey_id":"1",
# "answers":[
# {"question_id":1,"answer":"answer1"},
# {"question_id":2,"answer":"answer2"},
# {"question_id":3,"answer":"answer3"},
# {"question_id":4,"answer":"answer4"}
# ]
# }
In order to save to a t.json postgress column type, just pass the Hash survey object, like that:
YourModel.create(survey: survey)
Source: http://edgeguides.rubyonrails.org/active_record_postgresql.html
Try
{
survey: ¯\_༼◉ل͟◉༽_/¯,
}
Json may not be parsed if json have construction like this:
survey = {
}
Json may not contain = and assignment
Check real variables values with puts varname.inspect near at code lines where you meet unexpected behaviour.

Images from picasaweb on Rails

I need work with images from picasaweb on Rails (add, delete, view). I tried some gems (picasa, etc). But gem and json return only albums, images array is empty.
Use this gem with example:
require "picasa"
# get some photos in an album
client = Picasa::Client.new(user_id: "your-gmail-account#gmail.com", access_token: "oauth-access-token")
albums = client.album.list.entries
album = albums.find { |album| album.title == "New Album" }
photos = client.album.show(album.id).entries
photos.each { |photo| puts photo.title }
https://github.com/morgoth/picasa
https://github.com/morgoth/picasa/blob/master/examples/get_some_photos.rb

How to retrieve reference to AWS::S3::MultipartUpload with ruby

I have a rails app and in a controller action I am able to create a multipart upload like so:
def create
s3 = AWS::S3.new
bucket = s3.buckets["my_bucket"]
key = "some_new_file_name.ext"
obj = bucket.objects[key]
mpu = obj.multipart_upload
render json: {
:id => mpu.id
}
end
so now the client has the multipart upload id and she can upload parts to aws with her browser. I wish to create another action which will assemble the parts once they are done uploading. Something like:
def assemble
s3 = AWS::S3.new
bucket = s3.buckets["my_bucket"]
key = params['key']
bucket.objects[key].multipart_upload.complete
render json: { :status => "all good" }
end
This isn't working though. How do I retrieve a reference to the multipartUpload object or create a new one with the key or id so that I can call the "complete" method on it? Any insight is appreciated
I found this method in the documentation for the Client class and got it to work as follows:
client = AWS::S3::Client.new
# reassemble partsList
partsList = []
params[:partsList].each do |key, pair|
partsList.push pair
end
options = {
:bucket_name => 'my_bucket',
:key => params[:key],
:upload_id => params[:upload_id],
:parts => partsList
}
client.complete_multipart_upload(options)

Resources