I am sort of new to rails and I am trying to upload images directly to S3 with Shrine. I got direct uploads to S3 to work perfectly, however, when I introduced jquery file upload and upload an image, chrome console throws
this error
at me. I'm not sure what I'm doing wrong and I can't seem to find a solution anywhere online. I get that it's a presign error and it's probably not finding the cache link but I don't know how to resolve that.
EDIT: This was solved by including the presign code in the Routes file and altering the storage location in the uploads.js to the correct location. Now, however, I have an issue with the files being rolled back when they attempt to upload.
I'm using the cloud based ide C9,
This is my uploads.js file:
$(document).on("turbolinks:load", function(){
$("[type=file]").fileupload({
add: function(e, data) {
console.log("add", data);
data.progressBar = $('<div class="progress"><div class="determinate"
style="width: 70%"></div></div>').insertBefore("form")
var options = {
extension: data.files[0].name.match(/(\.\w+)?$/)[0], //set the
file extention
_: Date.now() //prevent caching
};
$.getJSON("/autos/upload/cache/presign", options, function(result) {
console.log("presign", result);
data.formData = result['fields'];
data.url = result['url'];
data.paramName = "file";
data.submit()
});
},
progress: function(e, data) {
console.log("progress", data);
var progress = parseInt(data.loaded / data.total * 100, 10);
var percentage = progress.toString() + '%'
data.progressBar.find(".progress-bar").css("width",
percentage).html(percentage);
},
done: function(e, data) {
console.log("done", data);
data.progressBar.remove();
var image = {
id: data.formData.key.match(/cache\/(.+)/)[1], // we have to
remove the prefix part
storage: 'cache',
metadata: {
size: data.files[0].size,
filename: data.files[0].name.match(/[^\/\\]+$/)[0], // IE return full
path
mime_type: data.files[0].type
}
}
form = $(this).closest("form");
form_data = new FormData(form[0]);
form_data.append($(this).attr("name"), JSON.stringify(image))
$.ajax(form.attr("action"), {
contentType: false,
processData: false,
data: form_data,
method: form.attr("method"),
dataType: "json"
}).done(function(data) {
console.log("done from rails", data);
});
}
});
});
My routes.rb file includes:
mount ImageUploader::UploadEndpoint => "/images/upload"
mount Shrine.presign_endpoint(:cache) => "/autos/upload/cache/presign"
I have a model which accepts these images as well as other fields called Autos, this is included in the Autos file:
include ImageUploader[:image]
My Autos Controller is:
class AutosController < ApplicationController
before_action :find_auto, only: [:show, :edit, :update, :destroy]
def index
#autos = Auto.all.order("created_at DESC")
end
def show
end
def new
#auto = current_user.autos.build
end
def create
#auto = current_user.autos.build(auto_params[:auto])
if #auto.save
flash[:notice] = "Successfully created post."
redirect_to autos_path
else
render 'new'
end
end
def edit
end
def update
if #auto.update(auto_params[:auto])
flash[:notice] = "Successfully updated post."
redirect_to auto_path(#auto)
else
render 'edit'
end
end
def destroy
#auto.destroy
redirect_to autos_path
end
private
def auto_params
params.require(:auto).permit(:title, :price, :description, :contact, :image, :remove_image)
end
def find_auto
#auto = Auto.find(params[:id])
end
end
Assuming your image_uploader.rb has the ImageUploader class defined and given that your presign endpoint is something like /autos/upload/cache/presign, your routes.rb should have the presign route defined like so:
mount ImageUploader.presign_endpoint(:cache) => '/autos/upload/cache/presign'
I hope this single change in the route file would make you able to get the presign object that should contain 3 keys: url, fields and headers
# GET /autos/upload/cache/presign
{
"url": "https://my-bucket.s3-eu-west-1.amazonaws.com",
"fields": {
"key": "cache/b7d575850ba61b44c8a9ff889dfdb14d88cdc25f8dd121004c8",
"policy": "eyJleHBpcmF0aW9uIjoiMjAxNS0QwMToxMToyOVoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJzaHJpbmUtdGVzdGluZyJ9LHsia2V5IjoiYjdkNTc1ODUwYmE2MWI0NGU3Y2M4YTliZmY4OGU5ZGZkYjE2NTQ0ZDk4OGNkYzI1ZjhkZDEyMTAwNGM4In0seyJ4LWFtei1jcmVkZW50aWFsIjoiQUtJQUlKRjU1VE1aWlk0NVVUNlEvMjAxNTEwMjQvZXUtd2VzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LHsieC1hbXotYWxnb3JpdGhtIjoiQVdTNC1ITUFDLVNIQTI1NiJ9LHsieC1hbXotZGF0ZSI6IjIwMTUxMDI0VDAwMTEyOVoifV19",
"x-amz-credential": "AKIAIJF55TMZYT6Q/20151024/eu-west-1/s3/aws4_request",
"x-amz-algorithm": "AWS4-HMAC-SHA256",
"x-amz-date": "20151024T001129Z",
"x-amz-signature": "c1eb634f83f96b69bd675f535b3ff15ae184b102fcba51e4db5f4959b4ae26f4"
},
"headers": {}
}
When upload starts, you will now find this object in developer console instead of the previous 404 not found error.
UPDATE
I think you are very close to the solution. In your create/update actions, use auto_params[:auto] instead of auto_params
You would also like to check the RoR guide on Association Basics for collection methods
I think you following the tutorial of gorails direct upload s3
in you gem file make sure you use the right roda version
gem 'roda', "~> 2.29.0"
Related
I had earlier been provided permission for the feature Manage_pages. However, Facebook has changed it policies and this feature has been depreciated, moreover, my application wasn't using much of the Facebook feature. For these 2 reasons, my app has been disabled.
SO, i submitted a review for the same. The feedback is as such:
The main purpose of my app is to take payments through the client's Facebook page , for which earlier used Manage_pages feature. Now, even if i hit the connect button, it says "The app is in dev mode" . Am stuck here, how can i get the button to work and display a screen cast if I keep getting the same error. this seems like an endless while loop :(
Now, when i am trying to re-submit an app review, it seems to be getting auto rejected.
Any insight would be appreciated!
Here is my Facebook controller code
class FacebookController < ApplicationController
skip_before_action :verify_authenticity_token
skip_before_action :authorize
def connect
# get array of facebook pages added
page_ids = params[:tabs_added].keys
# create or update connection for each facebook page added
page_ids.each do |page_id|
page = FacebookPage.where(page_id: page_id).first_or_initialize
page.update!(slug_id: params[:slug_id], form_type: params[:form_type])
end
head :created
end
def show
request = parse_signed_request(params[:signed_request]).try(:[], 'page')
facebook_page = FacebookPage.find_by(page_id: request.try(:[], 'id'))
facebook_admin = request.try(:[], 'admin')
if facebook_page
redirect_to contribution_form_url(
subdomain: facebook_page.account_type,
id: facebook_page.slug.name,
form_type: facebook_page.form_type,
iframe: true,
facebook: true,
facebook_admin: facebook_admin,
facebook_page: facebook_page
)
else
render nothing: true
end
end
def update
facebook_page = FacebookPage.find(params[:id])
slug = Slug.find_by!(name: page_params[:form_slug], account_type: facebook_page.account_type)
if facebook_page.update!(slug: slug, form_type: page_params[:form_type])
redirect_to contribution_form_url(
subdomain: facebook_page.account_type,
id: facebook_page.slug.name,
form_type: facebook_page.form_type,
iframe: true,
facebook: true,
facebook_admin: true,
facebook_page: facebook_page
)
end
end
private
def parse_signed_request(signed_request)
# We only care about the data after the '.'
payload = signed_request.split('.')[1]
# Facebook gives us a base64URL encoded string.
# Ruby only supports base64 out of the box, so we have to add padding to make it work
payload += '=' * (4 - payload.length.modulo(4))
decoded_json = Base64.decode64(payload)
JSON.parse(decoded_json)
end
def page_params
params.require(:facebook_page).permit(:form_type, :form_slug)
end
end
and i am also attaching the the script which opens the facebook tab
<script>
function move_to_top( value )
{
$(".fb_dialog").each(function(index) {
if($(this).css("top")!='-10000px') {
$(this).css("top", value + 'px' );
}
});
setTimeout( ('move_to_top("'+value+'");'), 1250);
}
window.addToFacebook = function() {
// make sure logged in as user; not page
FB.login(function(loginResponse) {
// if they are correctly logged in as user
if (loginResponse.authResponse) {
// popup modal to add form to page
FB.ui({
method: 'pagetab',
display: 'popup'
}, function(response) {
// if tabs were added, make the connection
if (Object.keys(response.tabs_added).length > 0) {
console.log("inside")
response.form_type = $('[name=form_type]:checked').val().slice(0,1);
response.slug_id = '<%= Slug.find_by(name: slug, account_type: candidate.account_type).try(:id) || candidate.account_slug.id %>';
$.post('/facebook/connect', response);
$.magnificPopup.open({
items: {
src: '<%=j render "form_settings/facebook_success" %>',
type: 'inline'
}
});
}
});
$(".fbProfileBrowserResult").ready( function(){
t = setTimeout ( ('move_to_top("'+50+'")'), 1250 );
});
}
});
};
</script>
<p><%= link_to 'Connect with Facebook', '#', onclick: 'addToFacebook()', class: 'button' %></p>
Hey everyone I am having an issue setting up my app. It uses the shopify API and essentially what it does is grab some data via a view and sends it to the controller but I am having issues passing it to another method in the controller to use the API to save the data.
Here is my code :
Controller
class BuilderController < ShopifyApp::AuthenticatedController
def index
urlval = request.fullpath
#urlCheck = urlval.split('/').last
end
def show
url = request.fullpath
#urlID = url.split('/').last
#customers = ShopifyAPI::Customer.search(query: "id:"+ #urlID)
#need to get a way to retrieve the ajax call info here to pass into the update
end
def updateCustomer(notes)
#customers.each do |cus|
cus.note = notes
cus.save()
end
end
def new
notes = params[:notes]
updateCustomer(notes)
render json: notes
end
end
View
<button id="test">TEST</button>
<script>
var butt = document.getElementById('test');
butt.addEventListener("click",function(){
$.ajax({
url: "/builder/new",
type: "GET",
data: {
"notes": [
"test",
"test2"
]
},
success: function(data,text,xhr) {
console.log(text);
console.log(xhr);
console.log(data);
alert('successfully');
},
error: function(data,error){
console.log(data);
console.log(error);
alert("help");
}
});
});
</script>
Rather than a fully separate method, have you looked into the
respond_to method? http://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_to
You could do (assuming html is the primary request type, change if it isn't):
def index
respond_to do |format|
format.html { actions }
format.json { actions }
end
end
This the method we use to accommodate different request types within the same action. Please let me know if I've misinterpreted your question.
you can use this
update_all(updates) public
Updates all records with details given if
they match a set of conditions supplied, limits and order can also be
supplied. This method constructs a single SQL UPDATE statement and
sends it straight to the database. It does not instantiate the
involved models and it does not trigger Active Record callbacks or
validations.
http://apidock.com/rails/v4.0.2/ActiveRecord/Relation/update_all
def new
notes = params[:notes]
#customer.update_all({note: notes})
respond_to do |format|
format.html {}
format.json { json: #customer.json }
end
end
I'm using the react-rails gem and have two models: Message and User. User has_many :messages.
In my message.js.jsx, I'd like to show the User of that message. In regular erb, it'd just be <%= message.user.name %>. How would I do this in the message.js.jsx component?
You could rename your component to message.js.jsx.erb and use ERB in it, but it will only be compiled once when Rails starts up.
A more React-ish way to handle is to AJAX load the user data in componentDidMount (or a Store, if using Flux).
message.js.jsx
getInitialState: function() {
return { user: { name: '' } };
},
componentDidMount: function() {
$.getJSON('/users/'+ this.props.id +'.json', function(userData) {
if (this.isMounted()) {
this.setState({ user: userData })
}
});
},
You can create a Rails endpoint to return userData as JSON something like this:
users_controller.rb
def show
#user = User.find(params[:id])
respond_to do |format|
format.html # default html response
format.json { render json: #user.to_json(only: [:id, :name]) }
end
end
See Facebook's page on this for more details
I agree with Unixmonkey that is the react way. You can also do it a few more ways.
#user = JSON.parse user.to_json(include: [:messages], only: [:id, :name])
As well as using componentDidMount to hit a JSON endpoint using jbuilder which you can put a timeout on if you want to update dynamically.
componentDidMount: function() {
$.getJSON('/users/'+ this.props.id +'.json', function(user) {
if (this.isMounted()) {
this.setState({ user: user })
}
});
},
Your show.json.jbuilder under user views would look something like this:
json.id #user.id
json.name #user.name
json.messages #user.messages do |message|
json.id message.id
json.content message.content
json.created_at message.created_at
end
I'm trying to let Angular JS and Ruby on Rails communicate for sharing some data in an example application.
I generated a resource called Entries, and made this controller:
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 generates a response in json with the Entries data. I seeded the Entries database:
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
Entry.create!(name: "name1")
Entry.create!(name: "name2")
Entry.create!(name: "name3")
Entry.create!(name: "name4")
Entry.create!(name: "name5")
Entry.create!(name: "name6")
Entry.create!(name: "name7")
I created some entries. I need to let Angular receive them. This is my js file:
var rafflerApp = angular.module('rafflerApp', ["ngResource"]);
rafflerApp.controller('RaffleCtrl', function ($scope, $resource) {
//entries list
Entry = $resource("/entries/:id", {id: "#id"}, {update: {method: "PUT"}})
$scope.entries = Entry.query();
//add a name to the list
$scope.addEntry = function(entry){
entry = Entry.save($scope.newEntry);
$scope.entries.push(entry);
$scope.newEntry = {}
}
//draw a winner
$scope.selectWinner = function(draw){
pool = [];
angular.forEach($scope.entries, function(entry){
if (!entry.winner){
pool.push(entry)
}
});
if (pool.length > 0){
entry = pool[Math.floor(Math.random()*pool.length)]
entry.winner = true
entry.$update(entry)
$scope.lastWinner = entry
}
}
});
If I try the application, I don't receive any js errors, but the list is empty. If I try to navigate to /entries/(casual :id), I receive this error:
ActionController::UnknownFormat in EntriesController#index
and it highlights this part of the code:
def index
respond_with Entry.all
end
Why did I receive this error? How can I let Ruby on Rails communicate data with Angular JS? I am also adding my routes file:
Rails.application.routes.draw do
resources :entries
root to: "raffle#index"
end
Update your route.rb to render JSON by default instead HTML
resources :entities, defaults: {format: :json}
None of the tutorials I seem do what I'm trying to do. Very simply, I want a user to be able to submit a POST request to a controller (to "LIKE" a video) and have the controller respond back with a JSON object. Any help would be appreciated.
Thanks
EDIT Because SO is messing the formatting up, here is a gist of my code too:
https://gist.github.com/813503
Here is my controller:
class LikesController < ApplicationController
before_filter :get_ids
respond_to :json, :js
def videolink
results = {}
# check to see if the user has liked this videolink before
if current_user
liked = Like.video?(current_user, #vid_id)
results["status"] = "OK"
results["liked"] = liked
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
def update
results = {}
if current_user
results["status"] = "OK"
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
private
def get_ids
#vid_id = params[:videolink_id]
end
end
Here is my JS file:
$("#likeVideo").click(function() {
$.ajax({
contentType: "application/json",
data: { game_id: game_id, videolink_id: current_video["videolink"]["id"] },
dataType: "json",
type: "POST",
url: "/likes/" + game_id,
success: function(data) {
console.log("Success", data);
}
});
return false;
});
My routes:
resources :likes do
collection do
get "videolink"
end
member do
post :update
end
end
And here is the error I get:
NoMethodError
in LikesController#update
undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>
If you want to send back custom JSON, Instead of respond_with(results.to_json)... just render the text
render :text=>results.to_json
The responds_with is a way for you to easily send back objects, with their location (url). So that's why your error is telling you that that '_url' is invalid.
More info on responds_with, courtesy of http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering
If another format was requested, (i.e.
:xml or :json)
If it was a GET request, invoke the :to_format method on the resource and
send that back
If the resource has validation errors, send back the errors in the
requested format with the
:unprocessable_entity status code
If it was a POST request, invoke the :to_format method on the resource
and send that back with the :created
status and the :location of the new
created resource
Else, send back the :ok response with no body