I'm trying to use the Rspotify gem (it's a wrapper for the Spotify API) to do a simple search for an artist -- basically something similar to what's outlined in this blog post.
The issue is that I get a different response when I'm running the search in my console vs. in my app via the UI. I should be getting the full data set on the UI like I do when I'm in the console.
Here's my form snippet:
<%= form_for :artist, url: artist_search_path, html: {class: "form-inline"} do |f| %>
<div class="form-group">
<%= f.text_field :artist_name, class: "form-control", placeholder: "Enter artist or group" %>
<%= f.submit "Search", class: "btn btn-success" %>
</div>
<% end %>
Two routes:
get 'profile', to: "pages#profile"
post 'artist_search', to: "artists#search"
Here's my artists controller snippet:
def search
if !params[:artist][:artist_name].blank?
#artists = RSpotify::Artist.search(params[:artist][:artist_name])
redirect_to profile_path
end
end
Here's a snippet of what I get when I submit an artist name on the UI and print out #artists in my logs:
Processing by ArtistsController#search as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"uzubTTE/bZvLBbU0MpY8lmLur1YPExnwdvXMXs882D7bm+fcUgTC8zRLizPh9Gp7eUjG2cGkNIGSk/Z+aZhrpg==", "artist"=>{"artist_name"=>"Drake"}, "commit"=>"Search"}
#<RSpotify::Artist:0x007faf454f4f60>
#<RSpotify::Artist:0x007faf454f4f10>
#<RSpotify::Artist:0x007faf454f4ec0>
# Bunch more of the above...
Redirected to https://website.com/profile
Completed 302 Found in 81ms (ActiveRecord: 0.0ms)
And I get a list of these when I run the search in the console:
[#<RSpotify::Artist:0x000000049f0bd8 #followers={"href"=>nil, "total"=>2645122}, #genres=["east coast hip hop", "hip hop", "pop rap", "rap", "southern hip hop", "trap music"], #images=[{"height"=>667, "url"=>"https://i.scdn.co/image/f58a98bc92cd2dc7020fc45a45eebb29380048ab", "width"=>1000}, {"height"=>427, "url"=>"https://i.scdn.co/image/9dd1bab34761764a125508534e443a9b245a9b56", "width"=>640}, {"height"=>133, "url"=>"https://i.scdn.co/image/620b2133ab3f20045c0d9669e706bbf11786cf78", "width"=>200}, {"height"=>43, "url"=>"https://i.scdn.co/image/5018ebe8a0d1060e6b39b2021132c082be1a913d", "width"=>64}], #name="JAY Z", #popularity=83, #top_tracks={}, #external_urls={"spotify"=>"https://open.spotify.com/artist/3nFkdlSjzX9mRTtwJOzDYB"}, #href="https://api.spotify.com/v1/artists/3nFkdlSjzX9mRTtwJOzDYB", #id="3nFkdlSjzX9mRTtwJOzDYB", #type="artist", #uri="spotify:artist:3nFkdlSjzX9mRTtwJOzDYB">]
Related
I am completing the Ruby Rails tutorial for a blog and when I try and submit a new post I am getting a ActionController::InvalidAuthenticityToken error from the browser.
I am new to Ruby Rails (hence why I am doing the tutorial) and I have been back through the examples and have looked a various other answers etc and I cannot seem to find what the problem could be? I would like to understand the problem and how to fix it as part of learning.
This is what is shown in the extracted source :
def handle_unverified_request
raise ActionController::InvalidAuthenticityToken
end
end
end
This is from the Server :
Parameters: {"authenticity_token"=>"MijxdOhNKeov89oetl7Xa0KWpSZoeb3WAIuX0RECyIusjfjs/B5megtnH6JFOSG1G5K7g+csApABCn31UxdYGg==", "article"=>{"title"=>"po request"
, "text"=>"I want to buy some cheese"}, "commit"=>"Save Article"}
HTTP Origin header (https://3000-dot-4708054-dot-devshell.appspot.com) didn't match request.base_url (https://127.0.0.1:3000)
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms | Allocations: 499)
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
And this is the .erb for a new record:
<%= form_with scope: :article, url: articles_path, local: true do |form|
%>
<% end %>
<%= link_to 'Back', articles_path %>
<%= form_with scope: :article, url: articles_path, local: true do |form|
%>
<p>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :text %><br>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
The authenticity token is used by rails to ensure that requests come from the site rails is expecting. When it generates a form, it includes the verification token for this purpose. There's a much better explanation of the history / why it's used here:
Understanding the Rails Authenticity Token
If you want to keep the checks in, then the short answer is to include
<%= form_authenticity_token %>
In any views that generate forms. This will ensure the correct token is in the form, and prevent the error from occuring
This is my first question on here, so I am hoping I have not asked it incorrectly.
I have a generic new action on my tickets controller. Whenever I load tickets/new, it is creating a new item in the DB and committing it.
Here is the output from the server when the page is loading.
Started GET "/tickets/new" for ::1 at 2016-02-10 21:14:47 -0800
Processing by TicketsController#new as HTML
Customer Load (0.4ms) SELECT `customers`.* FROM `customers` WHERE `customers`.`email` = 'tim#tim.com' LIMIT 1
(0.3ms) BEGIN
SQL (0.5ms) INSERT INTO `tickets` (`category`, `created_at`, `updated_at`) VALUES (3, '2016-02-11 05:14:47', '2016-02-11 05:14:47')
(6.4ms) COMMIT
Rendered tickets/_new_form.html.erb (23.3ms)
Rendered tickets/new.html.erb within layouts/application (48.4ms)
Rendered layouts/_user_nav.html.erb (0.8ms)
Rendered layouts/_navbar.html.erb (0.5ms)
Rendered layouts/_flashes.html.erb (0.5ms)
Rendered layouts/_minimal.html.erb (759.5ms)
Completed 200 OK in 893ms (Views: 822.1ms | ActiveRecord: 21.3ms)
This is the from the tickets controller.
def new
#ticket = Ticket.new
end
Here is the code for the form.
<%= form_for(#ticket, html: { class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<%= f.hidden_field(:category) %>
<%= f.hidden_field(:severity) %>
<br>
<%= f.form_group :summary do |f| %>
<%= f.label :summary, class: 'control-label col-md-2' %>
<div class='col-md-8'>
<%= f.text_field :summary, class: 'form-control' %>
<%= f.error_messages %>
</div>
<% end %>
<%= f.form_group :detail do |f| %>
<%= f.label :detail, class: 'control-label col-md-2' %>
<div class='col-md-8'>
<%= f.text_area :detail, class: 'form-control' %>
<%= f.error_messages %>
</div>
<% end %>
<br>
</div>
<div class="form-actions col-md-offset-2 col-md-10">
<%= f.submit 'Create', class: 'btn btn-primary' %>
<%= link_to "Cancel", tickets_path, class: 'btn' %>
</div>
<% end %>
Here are the relevant routes.
resources :tickets do
collection do
get :step_1
get :new_ticket
get :billing_new_1
get :internet_step_1
get :internet_step_2
get :internet_modem_reset
get :internet_step_1
get :internet_step_2
get :internet_create_1
get :internet_create_2
get :tv_step_1
get :tv_step_2
get :tv_step_3
get :tv_create_1
get :tv_create_2
get :tv_create_3
get :closed
get :sidenav
end
member do
put :close
end
resources :notes
resources :appointments
end
Help!!
--Tim
INSERT INTO `tickets` (`category`, `created_at`, `updated_at`) VALUES (3, '2016-02-11 05:14:47', '2016-02-11 05:14:47')
This is getting category (3) from somewhere, suggesting that there is some functionality somewhere which is saving the #ticket.
The simplest explanation I can see is that you have a before_action somewhere. It would benefit to show your entire TicketsController:
#app/controllers/tickets_controller.rb
class TicketsController < ApplicationController
before_action :set_user #-> something like this??
end
Since you're new, you can make your routes much more succinct (multiple resources):
#config/routes.rb
methods = %i(step_1 new_ticket billing_new_1 internet_step_1 internet_step_2 internet_modem_reset internet_create_1 internet_create_2 tv_step_1 tv_step_2 tv_step_3 tv_create_1 tv_create_2 tv_create_3 closed sidenav)
resources :tickets do
resources :notes, :appointments
collection do
methods.each {|method| get method }
end
put :close, on: :member
end
I ended up starting the whole ticket class over.
I think the error was in my html.
My guess is that the if statement with the bang was causing the ticket to save, because of an enum with that name on the model.
Here is what I think was the bad html.
<% if #ticket.category == :tv %>
Ok. Your tv is down, but your internet is still working.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.internet! %>
Ok. Your internet is down, but your tv is still working.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.billing %>
I am fresh out of questions.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.category == :internet_and_tv %>
Ok. Your cable and internet are both down.'%>
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.'%>
<% else #ticket.category == :plant %>
<%end%>
I had a form that I want user to answer every question, so I add a model-level validation.
I supposed if it pass validation, it should redirect to another page call "scenario" (I haven't finish it's view so it should show template missing). If it does not pass validation, it should render once again to the new page, remains the information already filled in, and show validation error.
But no matter I filled out those fields or not, when I click submit button, it always show me the index page instead of "new" or "scenario"(which should be template missing). It seems ignore what I have wrote in the action "create", and "create" is never been called.
I use rails c and insert a new record to test validation. It does work well, so I guess there is no problem for my model and validation.
I also try to make form_for redirect to "scenario" directly, to make sure it work well for form_for, and it does show templete missing to me, so there might be some problem for "create" itself. I really don't know what's going wrong.
<%= form_for #subject, :url => { :controller => 'appstores', :action => 'scenario' } do |f| %>
There is a similar question: rails form_for never invokes the create controller action to use redirect_to.
I had try to use "respond_with", not work. And also check my controller is named as appstroes_controller.rb with resources :appstores in routes.rb.
I use rails 4.2.4, ruby 2.0.0, and bootstrap 3, don't know whether the version cause those problem or not.
Any help would be appreciated, thanks!
app/controller/appstores_controller.rb
class AppstoresController < ApplicationController
def index
end
def new
#subject = Subjectinfo.new
end
def create
#subject = Subjectinfo.new(params[:subjectinfo])
if #subject.save
redirect_to :action => "scenario"
else # if not pass DB validation
render :action => :new
end
end
def scenario
end
end
app/view/appstores/new.html.erb
<%= form_for #subject, :url => { :controller => 'appstores', :action => 'create' } do |f| %>
<form class="form-horizontal">
<div class="form-group">
<%= f.label :username, "User Name:", :class=>"control-label", :for=>"username" %>
<% if #subject.errors[:username].presence %>
<span class="model-error"><%= #subject.errors[:username].join(", ") %></span>
<% end %>
<%= f.text_field :username, :autocomplete=>"off", :placeholder=>"User Name", :class=>"form-control", :id=>"username" %>
</div>
<div class="form-group">
<%= f.label :mobile_user, "Are you a mobile device user?", :class=>"control-label", :for=>"mobile_user" %>
<% if #subject.errors[:mobile_user].presence %>
<span class="model-error"><%= #subject.errors[:mobile_user].join(", ") %></span>
<% end %>
<div class="radio radio-primary">
<%= f.radio_button :mobile_user, "1", :id=>"mobile_user_1" %>
<%= f.label :mobile_user, "Yes", :class=>"control-label", :for=>"mobile_user_1" %>
</div>
<div class="radio radio-primary">
<%= f.radio_button :mobile_user, "0", :id=>"mobile_user_0" %>
<%= f.label :mobile_user, "No", :class=>"control-label", :for=>"mobile_user_0" %>
</div>
</div>
<div class="text-center">
<%= f.submit "NEXT", :class => "btn btn-default btn-outline btn-lg" %>
</div>
</form>
<% end %>
app/modle/subjectinfo.rb
(to support "attr_accessible" for rails 4, I had put "gem 'protected_attributes'" in my Gemfile)
class Subjectinfo < ActiveRecord::Base
validates_presence_of :username, :mobile_user
attr_accessible :username, :mobile_user
end
config/routes.rb
AppStore::Application.routes.draw do
match ':controller(/:action(/:id(.:format)))', :via => :all
root :to => "appstores#index"
resources :appstores
get "appstores/scenario"=>"appstores#scenario"
end
rake routes
Prefix Verb URI Pattern Controller#Action
/:controller(/:action(/:id(.:format))) :controller#:action
root GET / appstores#index
appstores GET /appstores(.:format) appstores#index
POST /appstores(.:format) appstores#create
new_appstore GET /appstores/new(.:format) appstores#new
edit_appstore GET /appstores/:id/edit(.:format) appstores#edit
appstore GET /appstores/:id(.:format) appstores#show
PATCH /appstores/:id(.:format) appstores#update
PUT /appstores/:id(.:format) appstores#update
DELETE /appstores/:id(.:format) appstores#destroy
appstores_rfscenario GET /appstores/rfscenario(.:format) appstores#rfscenario
Btw, here is what I saw form terminal, this is when I filled in all the fields.
Started POST "/appstores" for 127.0.0.1 at 2015-11-03 22:25:54 +0800
Processing by AppstoresController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7WV4Iw/0uHNSnuXpr8qa39oFEF9gZfKm8EyHGQna0o0=", "subjectinfo"=>{"username"=>"a1", "mobile_user"=>"1"}, "commit"=>"NEXT"}
Rendered appstores/index.html.erb within layouts/application (12.6ms)
Completed 200 OK in 91ms (Views: 88.0ms | ActiveRecord: 0.0ms)
Here is when I leave them blank, but no matter it is blank or not, it always render to index......
Started POST "/appstores" for 127.0.0.1 at 2015-11-03 22:25:54 +0800
Processing by AppstoresController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7WV4Iw/0uHNSnfuXpr8qa39oFEF9gZfKm8EyHGQna0o0=", "subjectinfo"=>{"esearch"=>""}, "commit"=>"NEXT"}
Rendered appstores/index.html.erb within layouts/application (12.6ms)
Completed 200 OK in 91ms (Views: 88.0ms | ActiveRecord: 0.0ms)
Remove the line match ':controller(/:action(/:id(.:format)))', :via => :all from your routes.rb file and never use it anymore. This pattern matches any route and it is on the first position, other routes in your file don't have a chance at all because of that.
I have a many-to-many relationship between Notes and Stacks. I am creating a form where a user can create a new note, with a title, body, and then a group of check boxes. The group of checkboxes are various Stacks. I want a user to be able to associate one or multiple Stacks with a particular note.
I am using the simple_form gem to do this. Everything is working except the Stacks will not save to the database. The title and body save, but not the Stacks. I have tested both sides of the relationship manually in the console, and they do yield the expected results -- it works.
One thing I notice when I watch what is going on in the Rails Server tab is Unpermitted parameters: stack_ids, as seen here:
Started POST "/notes" for 127.0.0.1 at 2014-10-06 16:00:21 -0600
Processing by NotesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gMpbaYio0qkPLLrR6ICG0IJ7XNoy3Rn4RHLm3vwUU+I=", "note"=>{"title"=>"asdfs ", "body"=>"asdfasdf asfsadf ", "stack_ids"=>["1", "2", ""]}, "commit"=>"Create Note"}
Unpermitted parameters: stack_ids
My notes_controller.rb has these params:
def notes_params
params.require(:note).permit(:title, :body, :stack_id)
end
My stacks_controller.rb has these params:
def stacks_params
params.require(:stack).permit(:title, :description, :note_id)
end
Here is the form:
<%= simple_form_for #note, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.input :title, placeholder: ":title", id: "note-form-title-field", class: "note-form-fields" %>
<%= f.input :body, placeholder: ":body", id: "note-form-body-field", class: "note-form-fields" %>
<%= f.association :stacks, as: :check_boxes %>
<%= f.button :submit %>
<% end %>
I have tried replacing :stack_id in the params with other variations, and always get the same result. Any ideas on how to get these Stacks to save to the database, associated with a note? Thanks.
This StackOverflow posting provides a detailed solution.
In summary, when declaring strong parameters, I needed to explicitly map the stack_ids key to an empty array in my notes_controller.rb file:
def notes_params
params.require(:note).permit(:title, :body, stack_ids: [])
end
I am using nested fields in a form with fields_for..I need to add multiple attachments dynamically and submit the form. In the console I am getting params for attachment as
"reminder"=>{"message_addl_attachments_attributes"=>{"1380913359931"=>{"attachment"=>#<File:/tmp/RackMultipart20131005-4343-1cxemfz-0>}}
Iam not sure how to handle this in controller and save the attachment. I have built the associations properly.
In the controller I am doing like this.
def create_reminder
#reminder = Reminder.new
#addl = #reminder.message_addl_attachments.build(params[:reminder][:message_addl_attachments])
#addl.save
end
Please find the full params in console.
Processing ReminderPluginController#create_reminder (for 127.0.0.1 at 2013-10-05 00:53:33) [POST]
Parameters: {"reminder"=>{"subject"=>"nkljkl", "body"=>"<p>jkljkljkl jlkj</p>", "email"=>"", "message_addl_attachments_attributes"=>{"1380914609923"=>{"attachment"=>#<File:/tmp/RackMultipart20131005-4488-1agtr7m-0>}}}, "controller"=>"reminder_plugin", "select_batch"=>{"batch"=>"2"}, "select_department"=>{"department"=>""}, "recipients"=>"20", "authenticity_token"=>"L0py7Xdsf7JSQGqn2bdoE7EXDVN9ZmNNSwl0dbHMkfM=", "action"=>"create_reminder", "commit"=>"Send"}
[paperclip] Saving attachments.
Redirected to http://localhost:3000/reminder/create_reminder
Completed in 459ms (DB: 217) | 302 Found [http://localhost/reminder_plugin/create_reminder]
But it is not saving it in my rails public directory... In the db it is saving null values also.. Please help.
==============
myview.html.erb
<% form_for #reminder, :url => { :action => "create_reminder"
},:html=>{:multipart=>true} do |l| %>
<div class="addl_attachments">
<% l.fields_for :attachments do |a| %>
<%= render "message_addl_attachment_fields",:f=>a %>
<% end %>
<div class="add_addl_attachment">
<%= link_to_add_addl_attachment "#{image_tag
"buttons/add_2.png" } #{t('add_txt')}", l, :attachments %>
</div>
</div>
</div>
<div id="submit-button">
<%=submit_tag "#{t('send')}", :class => 'button',
:disable_with => "#{t('please_wait')}" %>
</div>
<% end %>
What your first have to check:
Is ImageMagick installed and working
Does your form have the attribute "multipart=>true"
Hope this helps :)