Using Sidekiq for Active Job and getting ActiveJob::DeserializationError Posted: 20 Aug 2016 08:20 AM PDT I'm trying to use Sidekiq to run the below job. The job performs fine when not queued (perform_now) but fails when called as (perform_later), which uses Sidekiq. AddEmployeesToRoomJob.perform_now room ## works fine AddEmployeesToRoomJob.perform_later room ## breaks in Sidekiq Error: AddEmployeesToRoomJob JID-da24b13f405b1ece1212bbd5 INFO: fail: 0.003 sec 2016-08-20T14:57:16.645Z 19456 TID-owmym5fbk WARN: {"class":"ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper","wrapped" :"AddEmployeesToRoomJob","queue":"default","args": [{"job_class":"AddEmployeesToRoomJob","job_id":"0ba5bd30-e281-49a7-a93f- 6e50445183ac","queue_name":"default","priority":null,"arguments": [{"_aj_globalid":"gid://dragonfly/Room/1"}],"locale":"en"}],"retry":true, "jid":"da24b13f405b1ece1212bbd5","created_at":1471704675.739077,"enqueued _at":1471705036.6406531,"error_message":"Error while trying to deserialize arguments: Couldn't find Room with 'id'=1","error_class":"ActiveJob::DeserializationError","failed_at":14717 04675.946183,"retry_count":4,"retried_at":1471705036.644416} 2016-08-20T14:57:16.645Z 19456 TID-owmym5fbk WARN: ActiveJob::DeserializationError: Error while trying to deserialize arguments: Couldn't find Room with 'id'=1 2016-08-20T14:57:16.645Z 19456 TID-owmym5fbk WARN: /Users/tamlyn/.rvm/gems/ruby-2.2.3/gems/activerecord- 5.0.0.1/lib/active_record/relation/finder_methods.rb:357:in `raise_record_not_found_exception!' My Job class AddEmployeesToRoomJob < ApplicationJob queue_as :default def perform(room) employees = Employee.all if employees.length > 0 employees.each do |employee| UserRoom.create(user: employee, room: room) end end end end My Thoughts I don't understand why it can't find the room which I'm passing into the perform method. It's as though it somehow loses that variable in the queueifying / JSONifying of the job? The Sidekiq docs say "Unfortunately this means that if the [Room] record is deleted after the job is enqueued but before the perform method is called, exception handling is different." They suggest a workaround but I don't see how that would help me: rescue_from ActiveJob::DeserializationError do |exception| # handle a deleted user record end Thanks in advance for any help! |
Access-Control-Allow-Oirigin on a single Rails route Posted: 20 Aug 2016 08:11 AM PDT In my Rails app, I'm building a feature that allows users to embed data from the app on other sites using a Javascript snippet. My Javascript snippet makes a GET request to a route in my rails app that returns raw JSON. When snippet and the JSON share the same domain, everything works well, but I'm running into CORS issues when I embed the snippet on another site. Using the solution I found here, I've begun configuring my Rails app for CORS. In my application_controller.rb : before_filter :add_allow_credentials_headers def add_allow_credentials_headers response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] || '*' response.headers['Access-Control-Allow-Credentials'] = 'true' end def options head :status => 200, :'Access-Control-Allow-Headers' => 'accept, content-type' end In my routes.rb : get 'embed_json' => 'application#options', :via => [:options] However, when I hit the above route in my browser, the app no longer returns the JSON object—just a blank screen. There seem to be a number of conflicting approaches on how best to handle CORS on a single Rails route. Is there a "Rails way" to handle this requirement? |
Publish method doesn't work properly Posted: 20 Aug 2016 08:22 AM PDT I have an Entry model with a boolean column published , which is set to false by default. I wrote the following method in the model: def self.publish self.update(published: true) end and in my controller I have def publish @entry = Entry.find(params[:id] @entry.publish redirect_to entries_path end (I thought to make it similar to the calling of destroy method in the model). Finally, in my view I have this: <%= link_to "Publish", entries_path, method: :publish %> But when I click the link, the request is processed by create method and returns me the following error: ActionController::ParameterMissing in Multiflora::EntriesController#create param is missing or the value is empty: entry |
InvalidAuthenticityToken errors in mobile Posted: 20 Aug 2016 08:10 AM PDT I have read multiple questions and answers here on StackOverflow about InvalidAuthenticityToken and protect_from_forgery but get none the wiser. I have a website that get hundreds of these errors every day. They seem to be mainly (only?) from mobile but I have only verified that through samples. I understand why there is an AuthenticityToken and the need for adding <%= csrf_meta_tags %> in the application.html (which I have) as well as having protect_from_forgery in the application controller. I have both the csrf_meta_tags and: protect_from_forgery with: :exception in my Application controller, as is default. I realize I can "solve" the problem by removing protect_from_forgery but that would make me vulnerable for CSRF-attacks so that is not really a solution, is it? I could add an "except" for protect_from_forgery for the form posts that take place but that would leave me just as vulnerable, right? Edit: I tried accessing the form with my mobile with cookies disabled and experienced a 422 error. Couldn't get it to cause the exception though. Adding an exception for my "result" function removed that, but that makes it vulnerable I guess? I am now in a position where I can't have it since it causes error for hundreds of users per day and I can't remove it because I am afraid that it will make my website vulnerable for hacks. So, what can I do? Is there a decent middle ground? Is there any way I can alter the protect_from_forgery and still feel fairly confident that I will not have my database destroyed by hackers? I am not using any API for the site and all of the errors come from the same type of form. I understand there is a javascript part to this problem but not really how I can use that information to solve the problem. Thanks in advance! Example of exception that I get: An ActionController::InvalidAuthenticityToken occurred in calculations#result: ActionController::InvalidAuthenticityToken ------------------------------- Request: ------------------------------- * URL : http://www.example.com/calculation/result * HTTP Method: PUT * IP address : 217.214.148.251 * Parameters : {"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"udnClerrF5UWvg84uaD82TzmPx/vWssv2wN9UPqyn10UwXqbOwa2FBtnZ5Nfo7HPh9xbA2OSrrUNineW50XiYg==", "commit"=>"Calculate", "controller"=>"calculations", "action"=>"result", "id"=>"123"} * Timestamp : 2016-08-19 12:11:09 UTC * Server : 2696e83c-1538-434d-ab6d-4e16577698d0 * Rails root : /app * Process: 6 ------------------------------- Session: ------------------------------- * session id: "42b36aacc78102605cb3365922a550b1" * data: {"session_id"=>"42b36aacc78102605cb3365922a550b1", "_csrf_token"=>"KU43tmmXbxxgoabHrbejg+NWWP1tUVoWABNDqO8FiFI="} ------------------------------- Environment: ------------------------------- * CONTENT_LENGTH : 322 * CONTENT_TYPE : application/x-www-form-urlencoded * HTTP_ACCEPT : text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 * HTTP_ACCEPT_ENCODING : gzip, deflate * HTTP_ACCEPT_LANGUAGE : sv-se * HTTP_CONNECTION : close * HTTP_CONNECT_TIME : 0 * HTTP_COOKIE : __unam=91429fa-156a1632125-9bccf3-3; _ga=GA1.2.357545074.1471586444; _gat=1 * HTTP_HOST : www.example.com * HTTP_ORIGIN : http://www.example.com * HTTP_REFERER : http://www.kalkyleramera.se/calculation * HTTP_TOTAL_ROUTE_TIME : 0 * HTTP_USER_AGENT : Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_3 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13G34 Safari/601.1 * HTTP_VERSION : HTTP/1.1 * HTTP_VIA : 1.1 vegur * HTTP_X_FORWARDED_FOR : 217.214.148.251 * HTTP_X_FORWARDED_PORT : 80 * HTTP_X_FORWARDED_PROTO : http * HTTP_X_REQUEST_ID : 5e925192-d6ea-4cd3-b049-20010f11f2c2 * HTTP_X_REQUEST_START : 1471608669086 |
Cocoon gem inside a table in rails Posted: 20 Aug 2016 08:04 AM PDT I'm busy with a invoicing application and i'm trying to put a nested form from the cocoon gem inside a <tbody></tbody> . The nested form is working perfectly but it doesn't show up in the <tbody></tbody> but at some random place above the table head. I think it's because you can't have <div class=nested-fields></div> inside the table body but i'm not sure how to do it differently. i have this in my invoices/_form.html.erb : <div class="row"> <div class="col-sm-12"> <table class="table table-striped"> <thead> <tr> <th class="hidden-480"> Hoeveelheid </th> <th class="hidden-480"> Beschrijving </th> <th class="hidden-480"> Bedrag </th> <th class="hidden-480"> Totaal </th> <th class="hidden-480"> Btw(%) </th> </tr> </thead> <tbody> <%= f.fields_for :products do |product| %> <%= render 'product_fields', f: product %> <%= link_to_add_association 'Item toevoegen', f, :products, class: 'btn btn-primary btn-success' %> <% end %> </tbody> </table> </div> </div> invoices/_product_fields.html.erb <div class="nested-fields"> <tr> <td> <%= f.text_field :quantity %> </td> <td> <%= f.text_area :description %> </td> <td> <%= f.number_field :unitprice %> </td> <td> €200 </td> <td> <%= f.select(:btw, [[' 21%', 21, title: '21%'],[' 6%', 6, title: '6%'], [' 0%', 0, title: '0%']]) %> </td> </tr> <%= link_to_remove_association 'x', f, class: 'btn btn-primary btn-danger' %> </div> Any idea what's going on? Help would be much appreciated! |
When using rspec to test ruby, I get repeated uninitialized constant errors. What am I doing wrong? Posted: 20 Aug 2016 07:26 AM PDT I have to start using rspec for a course I am taking and I am having lots of trouble. It keeps telling me that I have an Name Error uninitialized constant. My files are in the same folder. Here is the code in the two separate files. require_relative 'Ricks' describe Ricks do end and in the other file class Ricks end (shouts out to rick and morty) |
Factory Girl, issue with InvalidRecord error Posted: 20 Aug 2016 07:03 AM PDT I have problem with with error: ActiveRecord::RecordInvalid caused by this: let(:ind2){ build(:ind2) } Rspec test: describe '#client_free_time_validation' do let(:ind) { create(:ind).tap {|e| p e.valid?; p e.errors}} let(:ind2){ build(:ind2).tap {|e| p e.valid?; p e.errors} } context 'when training is during another training' do it 'raises an error' do expect(ind.valid?).to be_truthy expect(ind2.valid?).to be_falsey # expect(ind2.errors.count).to eq 1 # expect(ind2.errors[:base]).to eq(['Masz w tym czasie inny trening.']) end end Factory: FactoryGirl.define do factory :individual_training do date_of_training { Date.today.next_week.advance(days: 1) } association :client, factory: :client association :trainer, factory: :trainer start_on Time.parse('12:30') end_on Time.parse('13:30') association :training_cost, factory: :tc2 factory :ind do start_on Time.parse('11:00') end_on Time.parse('12:00') end factory :ind2 do start_on Time.parse('10:30') end_on Time.parse('11:30') end end end I'm confuse, because similar let working in another test. I tried debugging by using tap method but it doesn't show error messages(in another cases nice presents). If I should put some additional data(how looks like model etc.) please write. I saw that if I comment first let or second test pass. It looks at situations like two let(ind and ind2) coudn't work together. Example values of attributes generate by test: #<ActiveModel::Errors:0x00000001f4ade8 @base=#<IndividualTraining id: nil, date_of_training: "2016-08-23", client_id: 28, trainer_id: 29, start_on: "2016-08-20 11:00:00", end_on: "2016-08-20 12:00:00", training_cost_id: 4>, @messages={}> Have you suggestion how to debug what record is invalid? |
Handle post request in backbone Posted: 20 Aug 2016 06:40 AM PDT New to backbone, I am building a backbone application which uses rails APIs. This application involves PayU integration. I am able to send POST parameters to PayU (via submitting a hidden form) to initiate the gateway. Following are the code snippets i had used: <form id = "payu_post_form" action = "{{payu_post_form_url}}" method="POST"> <input type="hidden" name="key"/> <input type="hidden" name="txnid"/> <input type="hidden" name="amount"/> <input type="hidden" name="productinfo"/> <input type="hidden" name="firstname"/> <input type="hidden" name="email"/> <input type="hidden" name="phone"/> <input type="hidden" name="hash"/> <input type="hidden" name="service_provider"/> <input type="hidden" name="surl"/> <input type="hidden" name="furl"/> </form> $.ajax({ url: URL['buyCourse'](course_id), type: 'GET', crossDomain: true, xhrFields: { withCredentials: true }, beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')); }, success: function(res, status, xhr){ /////// setting values to hidden tags of payu_post_form _.each(res, function(value, key, payu_payload){ $('input[name="'+key+'"]').attr('value', value); }); $('input[name="surl"]').attr('value', CONSTANTS.payu_success_url); $('input[name="furl"]').attr('value', CONSTANTS.payu_failure_url); $('form#payu_post_form').submit(); }, error: function(res, status){ alert(res.message); } }).complete( function(){ }); But i am stuck capturing the response from PayU in my Backbone application, as PayU send response parameters via POST request that i need to capture in my backbone application and then further send to rails API. How backbone route handled POST requests? Is there anyway i could do that? If not, then kindly let me know a different approach to implement this. Any help will be appreciated. |
Paperclip 5.1.0 - undefined method [] for nil after update Posted: 20 Aug 2016 05:45 AM PDT I am using paperclip to store images. After updating to 5.1.0 (released tonight) I get the following error: undefined method `[]' for nil:NilClass My code in the view is this: <%= @company.pic1.url(:large)%> A change in 5.1.0 is the switch to leave s3_protocol as an empty string, if not set in the app: Is it possible to configure Paperclip to produce HTTPS urls? Following the advice there, I tried setting that string in the model to "http", "https" and :https, but didnt solve the problem. What could be wrong? This is my model: has_attached_file :pic1, :styles => { :large => "1000x600", :mid => "400x160", :thumb => "120x80>" }, :default_url => "https://s3.eu-central-1.amazonaws.com/server.assets/images/missing/image_missing_:style.png", :storage => :s3, :s3_credentials => APP_CONFIG["s3"], :path => ":class/:attachment/:style/:id.:extension", :s3_region => "eu-central-1", :s3_protocol => "http" Thank you for any ideas how to solve this. |
How to access YML file in rails Posted: 20 Aug 2016 05:53 AM PDT I have set up a settings.yml file in my config folder with some list elements I want to pass to my enumerize in my rails model : config/ settings.yml enumerize: hotel_status: - "Hotel Privé" - "Bâtiment Publique" - "CHRS" - "CADA" - "Centre d'accueil" - "Camping" - "Autres" I am trying to pass the list inside my Hotel model to enumerize this way : enumerize :status, in: Settings.enumerize.hotel_status but I am getting uninitialized constant Hotel::Settings How can I pass the list in the YML to enumerize. |
LoadError in Controller#index Posted: 20 Aug 2016 08:03 AM PDT I created a polymorphic relation in a book reviewing app that I am writing. My app has the nested models: Piece >> Section >> Subsection >> Subsubsection, and I have created a model which belongs to all of these called KeyConcept, my intention being that each of these can have a key concept. I am getting an error that I don't understand when trying to display the index action of the keyconcepts controller. I think it might be due to a naming conflict but I don't have enough experience to understand it. the error I am getting looks like this: Unable to autoload constant KeyConceptsController, expected /home/david/Documents/Learning/StuddyBuddy/app/controllers/key_concepts_controller.rb to define it else require_or_load(expanded, qualified_name) raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false) return from_mod.const_get(const_name) end elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix) My keyconcepts controller looks like this: key_concepts_controller.rb class Key_conceptsController < ApplicationController include KeyconceptsHelper def whereami if params[:piece_id] @piece = Piece.find(params[:piece_id]) @keyconcept = @piece.key_concepts.find(params[:id]) here = @piece parameter = :piece_id type = "Piece" elsif params[:section_id] @section = Section.find(params[:section_id]) @piece = @section.piece_id @keyconcept = @section.key_concepts.find(params[:id]) here = @section parameter = :section_id type = "Section" elsif params[:subsection_id] @subsection = Subsection.find(params[:subsection_id]) @section = @subsection.section_id @piece = Section.find(id=@section).piece_id here = @subsection parameter = :subsection_id type = "Subsection" elsif params[:subsubsection_id] @subsubsection = Subsubsection.find(params[:subsubsection_id]) @subsection = @subsubsection.subsection_id @section = Subsection.find(id=@subsection).section_id @piece = Section.find(id=@section).piece_id here = @subsubsection parameter = :subsubsection_id type = "Subsubsection" end end def redirect if type == "Piece" @redirect = redirect_to piece_path(@piece) elsif type == "Section" @redirect = redirect_to piece_section_path(@piece, @section) elsif type == "Subsection" @redirect = redirect_to piece_section_subsection_path(@piece, @section, @subsection) elsif type == "Subsubsection" @redirect = redirect_to piece_section_subsection_subsubsection_path(@piece, @section, @subsection, @subsubsection) end end def index whereami.call @piece = Piece.find(params[:piece_id]) @keyconcept = @piece.key_concepts.find(params[:id]) @redirect = redirect.call end def show whereami.call redirect.call end def new @keyconcept = KeyConcept.new @keyconcept.conceptable_id = here.id end def create whereami.call @keyconcept = KeyConcept.new(keyconcept_params) @keyconcept.conceptable_id = params[parameter] @keyconcept.conceptable_type = type @keyconcept.save redirect.call end def destroy here.destroy redirect.call flash.notice = "#{type} '#{here.name}' from '#{@piece.name}' deleted!" end def edit whereami.call end def update whereami.call here.update(keyconcept_params) flash.notice = "#{type} '#{here.name}' Updated!" redirect.call end end the link comes from the show action of the parent Piece model here: <% @piece.key_concepts.each do |concept| %> <li> <%= link_to concept.definition, [@piece, @keyconcept] %> <!-- we didn't use #piece_key_concept_path(@piece, @keyconcept), class: 'section_name' and it worked --> </li> How do I link to the keyconcepts "show" action by the way? I havent been able to so i just linked to the index action :/ So the routes.rb file looks like this: resources :pieces do resources :sections do resources :subsections do resources :subsubsections end end resources :links end resources :pieces, :sections, :subsections, :subsubsections do resources :connections, only: [:index, :new, :edit, :update, :destroy, :create] resources :keyconcepts, only: [:index, :new, :edit, :update, :destroy, :create, :show] end key_concept.rb class KeyConcept < ActiveRecord::Base belongs_to :conceptable, polymorphic: true end piece.rb class Piece < ActiveRecord::Base include Connectable include Conceptable has_many :sections has_many :subsections, through: :sections has_many :links end in models/concerns/conceptable.rb module Conceptable extend ActiveSupport::Concern included do has_many :keyconcepts, as: :conceptable end end |
How to compare arrays inside an array with each other in ruby? Posted: 20 Aug 2016 06:55 AM PDT [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ] [ 'a', 'b', 'b', 'z' ] & [ 'a', 'b', 'c' ] #=> [ 'a', 'b' ] I need the intersection of each array with all other arrays within an array. So the array could look like -> a = [[1, 2, 3], [3, 4, 5], [4, 5, 6],[1,"a","b"]] Now I need to compare them with each other and return an array of arrays with the given results from the intersection method. Anyone an idea? I tried the .next operator within a loop, but it is not supported for arrays in ruby 2.3.0 yet. something like: a.each_with_index do |a, i| a.length.times.each_with_index |j| p c[i]& c[i+1](***or c[i].next; end But that didn't work. |
Redcarpet Footnotes extension not working Posted: 20 Aug 2016 07:11 AM PDT I am trying to get linked footnotes to work but somehow Redcarpet simply is not recognizing the footnote extension I am passing into the initialiser. I am running Redcarpet version 3.3.4, which should have the footnotes functionality merged into master as discussed in these posts: Post 1 Post 2 Customer Renderer class CustomMarkdownParser < Redcarpet::Render::HTML include ActionView::Helpers::UrlHelper include ActionView::Helpers::AssetTagHelper include AbstractController::Rendering def block_code(code, language) Pygments.highlight(code, lexer: language) end def parse_media_link(link) end def image(link, title, alt_text) end def link(link, title, content) end def footnote_def(content, number) end def footnote_ref(number) end end markdown function in application_helper def md_parser(content) puts "Parsing Markdown" renderer = CustomMarkdownParser.new( hard_wrap: true, filter_html: true, with_toc_data: true) options ={ } markdown = Redcarpet::Markdown.new(renderer, autolink: true, # detect links and wrap them in link tags no_intra_emphasis: true, # ensures _ inside words are not repolaced with <em> tags disable_indented_code_blocks: true, # does not convert lines prefixed with 4 spaces fenced_code_blocks: true, lax_spacing: true, strikethrough: true, footnotes: true, superscript: true, tables: true, underline: true ) markdown.render(content).html_safe end I had a look atthe gem's code and it lists the following extensions: EXTENSION_MAP = { # old name => new name :autolink => :autolink, :fenced_code => :fenced_code_blocks, :filter_html => :filter_html, :hard_wrap => :hard_wrap, :prettify => :prettify, :lax_htmlblock => :lax_spacing, :no_image => :no_images, :no_intraemphasis => :no_intra_emphasis, :no_links => :no_links, :filter_styles => :no_styles, :safelink => :safe_links_only, :space_header => :space_after_headers, :strikethrough => :strikethrough, :tables => :tables, :generate_toc => :with_toc_data, :xhtml => :xhtml, # old names with no new mapping :gh_blockcode => nil, :no_tables => nil, :smart => nil, :strict => nil } I am not sure why footnotes is not included. |
What websocket to use with WebRTC on Rails? Posted: 20 Aug 2016 05:12 AM PDT I am trying to implement WebRTC on Rails, which is a tough task because I am new to Rails and web conferencing. I have followed a tutorial on http://www.tutorialspoint.com/webrtc/ but it appears we need a websocket installed for this to work. I tried a few but have been hitting some walls. I then finally tried web-socket-js with which I could actually get the websocket object on the client side but my setup is still having issues getting the websocket server object on the server.js side. Does anyone know what websocket would work best with Rails/WebRTC or is there something fundamental that I am missing from this documentation? |
How to resolve ffi_c (Load Error) Posted: 20 Aug 2016 04:44 AM PDT I want to deploy the middleman project to ftp server, but i am getting this error when I am trying install middleman-deploy plugin in GEMFILE C:\xampp\htdocs\myApp\testApp>bundle exec middleman C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/ffi-1.9.6-x64-mingw32/lib/ffi.rb:16:in `require': cannot load such file -- ffi_c (LoadError) from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/ffi-1.9.6-x64-mingw32/lib/ffi.rb:16:in `rescue in <top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/ffi-1.9.6-x64-mingw32/lib/ffi.rb:3:in `<top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/win32-file-0.8.1/lib/win32/file/constants.rb:1:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/win32-file-0.8.1/lib/win32/file/constants.rb:1:in `<top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/win32-file-0.8.1/lib/win32/file.rb:1:in `require_relative' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/win32-file-0.8.1/lib/win32/file.rb:1:in `<top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/ptools-1.3.2-universal-mingw32/lib/ptools.rb:2:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/ptools-1.3.2-universal-mingw32/lib/ptools.rb:2:in `<top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy/methods/ftp.rb:2:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy/methods/ftp.rb:2:in `<top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy/methods.rb:2:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy/methods.rb:2:in `<top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy/commands.rb:5:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy/commands.rb:5:in `<top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy.rb:3:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy.rb:3:in `<top (required)>' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:86:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:86:in `block (2 levels) in require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:81:in `each' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:81:in `block in require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:70:in `each' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:70:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler.rb:102:in `require' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-core-3.3.7/lib/middleman-core/load_paths.rb:37:in `setup_load_paths' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/middleman-core-3.3.7/bin/middleman:10:in `<top (required)>' from C:/Ruby23-x64/bin/middleman:22:in `load' from C:/Ruby23-x64/bin/middleman:22:in `<main>' When I remove gem "middleman-deploy" it works on localhost . |
Specified 'sqlite3' for database adapter, but the gem is not loaded. Add `gem 'sqlite3'` to your Gemfile Posted: 20 Aug 2016 05:12 AM PDT I have read all answers on this topic here but nothing works I am on windows 7 and Ruby2.2.0 |
Optimize this validation and initialization Posted: 20 Aug 2016 03:45 AM PDT I have a very special solution on a Rails 4.2 website where I have many complicated calculations. The problems I have consider validation and initialization. I create a separate class for each calculation and all look virtually the same way, as can be seen below (code simplified to be easier to overlook). I am out a bit on thin ice here since I have not done anything like this before and some of it is "trial and error programming" but it works. I am using the code in controllers etc using PUT requests like this: C_9.calculate_me(params) where params could look like this: {"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"...", "start_date"=>"2016-08-20", "nbr_of_days"=>"90", "commit"=>"Calculate", "controller"=>"calculations", "action"=>"result", "id"=>"9"} The code class C_9 include ActiveModel::Validations include ValidationFunctions attr_accessor :start_date, :nbr_of_days validates_length_of :start_date, :minimum => 8, :message => "value_is_not_a_proper_date" validates_numericality_of :nbr_of_days, :greater_than => 0, :message => "value_must_be_number_over_zero" validate :validate_buggy_start_date def initialize(params = {}, options = {}) @start_date = params[:start_date] @nbr_of_days = params[:nbr_of_days] end def calculate_me(params) @start_date = @start_date.to_date result_date = @start_date + @nbr_of_days.day end end Validation functions These are validation functions that are common for many different calculations. def validate_buggy_start_date # Don't know why the validate_start_date will not work for this... errors.add(:start_date, 'value_is_not_a_proper_date') unless validate_date(start_date) end def validate_date(this_date) begin Date.parse(this_date) this_date.to_date rescue proper_date = false else proper_date = true end end What I need help with The system is working but there are certain issues I need to optimize: Is there any way I can validate a date in ValidationFunction without having to create a new function (like def validate_buggy_start_date ) for every date that is named differently. Is there any way I can use the validate_date() -function right away from C_9 (i.e. without having to go through validate_buggy_start_date)? I would like to initialize the parameters and at the same time make sure they are float/string/date etc with for example variable.to_date . I can't, however, since the initialization is done before the validations so it will crash the app. I now solve it by re-establishing them in the calculate_me() -function but it does not feel very DRY. Is there any way around this? For some reason that I cannot understand I need to name the variables exactly like the attribute name, for example @nbr_of_days needs to be named just that. If I name it @day_numbers it will not work (the value will not be set). Why is it so? Is there a smarter way around it? In short, please help me make this functionality smarter and more DRY, if possible! |
Trying to configure environment variables using fb app_id and app_secret Posted: 20 Aug 2016 06:38 AM PDT I am following rails cast #85 here and the marked correct answer on stackoverflow here. I am trying to use facebook "app_id" and "app_secret" to set as environment variables in rails. my code is: initializers/facebook.rb FACEBOOK_CONFIG = YAML.load_file("#{::Rails.root}/config/facebook.yml")[::Rails.env] config/facebook.yml development: app_id: abcdefg app_secret: 123456 production: app_id: abcdefg app_secret: 123456 initializers/omniauth.rb OmniAuth.config.logger = Rails.logger Rails.application.config.middleware.use OmniAuth::Builder do provider :facebook, FACEBOOK_CONFIG['abcdefg'], FACEBOOK_CONFIG['123456'], {:client_options => {:ssl => {:ca_file => Rails.root.join("cacert.pem").to_s}}} end When I set the environment variables in front of the app_id and app_secret ie FACEBOOK_CONFIG when I try login through facebook it returns a "app_id parameter is required" message. So this way is not working. I am wondering if there is some code missing or someone can see something I am doing wrong the environment variables are not being processed through facebook (where they were before without any ENV variables). |
Rails not running migrations Posted: 20 Aug 2016 04:36 AM PDT I'm experiencing a really strange issue where rails won't execute migrations on my machine. I'm using Rails 4.2.5, Ruby 2.3.1p112, and Postgres 9.5.3 on OS X 10.11.6. The database creates/migrates and functions properly at Heroku and on another Mac with the same versions of everything. If I import the database from Heroku or the other machine I get a pending migration error when running rails s , even when I'm on the same exact source version. Running a db:schema tells me: You have 23 pending migrations: 20160627035230 DeviseCreateUsers 20160627035442 CreatePages 20160627055031 AddHeroToPages 20160627061237 AddAdministratorToUser 20160627061943 AddNameToUser 20160628042547 CreateSchools 20160628042702 CreateLicenses 20160628042841 JoinUsersAndSchools 20160628043323 AddJoinCodeToSchools 20160630012028 AddExpiryToLicenses 20160630024743 CreatePurchases 20160630043846 AddOmniauthToUsers 20160704003626 CreateMyIndustries 20160704010403 CreateMyCareers 20160704013913 CreateMyQuestions 20160704074916 AlterMyQuestionsDrop 20160704075947 AlterMyQuestionsChange 20160705071702 CreateUserAttributes 20160710235339 CreateAccessabilities 20160711000000 AddToAccessabilities 20160711044815 CreateMedia 20160711045327 AddLocaleToMedium 20160814010549 CreateInvoices Run `rake db:migrate` to update your database then try again. Running the migration then tells me: ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Invoke db:load_config (first_time) ** Execute db:load_config ** Execute db:migrate ActiveRecord::SchemaMigration Load (0.3ms) SELECT "schema_migrations".* FROM "schema_migrations" ** Invoke db:_dump (first_time) ** Execute db:_dump ** Invoke db:schema:dump (first_time) ** Invoke environment ** Invoke db:load_config ** Execute db:schema:dump ActiveRecord::SchemaMigration Load (0.2ms) SELECT "schema_migrations".* FROM "schema_migrations" Listing tables in psql only shows the schema_migrations: 20:09 $ rails db psql (9.5.3) Type "help" for help. mytalents_development=# \dt List of relations Schema | Name | Type | Owner --------+-------------------+-------+---------------- public | schema_migrations | table | aidancornelius (1 row) mytalents_development=# I also seem to get strange errors with db:migrate:up 20:11 $ rake db:migrate:up rake aborted! ActiveRecord::UnknownMigrationVersionError: No migration with version number 0 /usr/local/lib/ruby/gems/2.3.0/gems/activerecord-4.2.5/lib/active_record/migration.rb:939:in `run' /usr/local/lib/ruby/gems/2.3.0/gems/activerecord-4.2.5/lib/active_record/migration.rb:834:in `run' /usr/local/lib/ruby/gems/2.3.0/gems/activerecord-4.2.5/lib/active_record/railties/databases.rake:82:in `block (3 levels) in <top (required)>' /usr/local/lib/ruby/gems/2.3.0/gems/rake-11.2.2/exe/rake:27:in `<top (required)>' Tasks: TOP => db:migrate:up (See full trace by running task with --trace) Does anyone have any insight about what might be going on here? Other projects in Rails 4 and Rails 5 work on this machine, but this one just won't. Thanks in advance for any suggestions! |
ERROR: While executing gem ... (Gem::Package::FormatError) package metadata is missing in profile.gem Posted: 20 Aug 2016 07:59 AM PDT I use OS X El Capitan 10.11.6 First,i have problem with installing pods and able to find the problem after follow step in this site..the terminal spell the problem out it was ruby v 2.2.2 after I installed it I get new problem when I try to install cocoapods $ sudo gem install cocoapods Password: ERROR: While executing gem ... (Gem::Package::FormatError) package metadata is missing in profile.gem Any help would be really appreciated. Thanks ! |
store website invite token parameter during FB login Posted: 20 Aug 2016 05:57 AM PDT A user can share our website url with his invite token as www.weburl.com/invite_token . Then a user can signup using his FB account. After logging in am loosing the invite token because of FB login. How do I propagate or save this invite_token after auth/facebook/callback to my login page. Gems used in my app are: gem 'omniauth-facebook' gem 'koala' |
How to write Regex to not allow this phone number with newline character? Posted: 20 Aug 2016 03:04 AM PDT I have problem to write regex to pass last test with phone number value equal "+48 999 888 777\naseasd". Here are my files. What I'm doing wrong? app/models/user.rb class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable validates :phone_number, format: { with: /[+]?\d{2}(\s|-)\d{3}(\s|-)\d{3}(\s|-)\d{3}/, allow_nil: true } end spec/models/user_spec.rb require 'rails_helper' describe User do it { is_expected.to allow_value('+48 999 888 777').for(:phone_number) } it { is_expected.to allow_value('48 999-888-777').for(:phone_number) } it { is_expected.to allow_value('48 999-888-777').for(:phone_number) } it { is_expected.not_to allow_value('+48 aaa bbb ccc').for(:phone_number) } it { is_expected.not_to allow_value('aaa +48 aaa bbb ccc').for(:phone_number) } it { is_expected.not_to allow_value("+48 999 888 777\naseasd").for(:phone_number) } end Error in console is: Failures: 1) User should not allow phone_number to be set to "+48 999 888 777\naseasd" Failure/Error: it { is_expected.not_to allow_value("+48 999 888 777\naseasd").for(:phone_number) } Expected errors when phone_number is set to "+48 999 888 777\naseasd", got errors: ["can't be blank (attribute: \"email\", value: \"\")", "can't be blank (attribute: \"password\", value: nil)"] # ./spec/models/user_spec.rb:9:in `block (2 levels) in <top (required)>' |
How to assign current_user.id to micropost.user_id in react-rails? Posted: 20 Aug 2016 02:17 AM PDT I'm new to react-rails, my repo is at https://github.com/yogabread/react_try I'm trying to assign the current_user.id to each micropost, but I don't know how to do it using react. I don't know the proper syntax for doing it from the view by adding hidden input, and building it from the controller @micropost.user_id = current_user.id doesn't work. How can I put hidden fields like the one below in an x.js.jsx file? = f.hidden_field :user_id, value: current_user.id My _new_micropost.js.jsx has: render() { return ( <div> <input ref='content' placeholder='Post your updates here' /> WRONG <input type="hidden" name="user_id" value={ current_user.id } /> <button onClick={this.handleClick} className="btn btn-success btn-sm">Submit</button> </div> ) } |
Customizing fields with the administrate gem for rails Posted: 20 Aug 2016 01:31 AM PDT I cannot seem to find any documentation on how to modify the administrate gem's default dashboards in order to customize what gets displayed in the index and show pages. Here's my specific goal: - Given that an
Article belongs_to an Author - When I create an Article
- I want to see the Author's last name in the dropdown list for the associated field
- And once saved, I want to see the Author's last name in the Article's index and show pages
Right now, instead, I get a not-so-useful "Author #4" as the record label. Here's the automatically generated dashboard: class ArticleDashboard < Administrate::BaseDashboard ATTRIBUTE_TYPES = { author: Field::BelongsTo, id: Field::Number, title: Field::String, content: Field::Text, created_at: Field::DateTime, updated_at: Field::DateTime, }.freeze [snip] end The "Customizing Dashboard" documentation page says: Each of the Field types take a different set of options, which are specified through the .with_options class method. So I figure that calling with_options on Field::BelongsTo might be the way to go, but what options are available for that field (or for any other, for that matter)? |
Rails 5 ActiveModel::Model error when initialising class with no params (MyClass.new) Posted: 20 Aug 2016 01:39 AM PDT When running a test, if I try to create a new object using User.new I get an error. If instead I use User.new({}) , it works fine. Isn't params supposed to be defaulted to empty if not passed in? $ rails -v Rails 5.0.0.1 user.rb class User include ActiveModel::Model attr_accessor :name, :email, :country end user_test.rb require 'test_helper' class User < ActiveSupport::TestCase test "should create an empty user when initialized with no params" do user = User.new assert_not_nil(user, 'user cannot be empty') end end test result Error: User#test_should_create_an_empty_user_when_initialized_with_no_parameters: ArgumentError: wrong number of arguments (given 0, expected 1) test/models/user_test.rb:7:in `new' test/models/user_test.rb:7:in `block in <class:User>' |
append existing values in table as string Posted: 20 Aug 2016 02:42 AM PDT On submit action (from my standard RoR edit view), I want to store existing data fields as an ongoing textdump in the same row. The controller should "push" the value of a data field (e.g. current_location ) to a text in the tablefield logdump with \n as a separator. After some travelling and changes of "current_location" there will be e.g. the following text stored in the tablefield logdump : London Rio Athen Berlin New York I thought about storing this log in a extra log table, but this string dump solution into my existing table, is enough for my needs. |
Syntax error in js while using global variable Posted: 20 Aug 2016 01:14 AM PDT Actually I do have problems with maintaining gem gon. While waiting for the answer on gon from TL I need to set my stuff working, so I've tried global variable. Looks like this in create_comment.jst.skim <div class="panel" id="question_comment_#{@comment_id}"> <div class="panel-heading">#{@user_name}</div> <div class="panel-body">#{@comment_body}</div> <a class="delete_comment" href="/comments/#{@comment_id}" data-method="delete" rel="nofollow" data-remote="true" data-confirm="Are you sure?">Delete<a> </div> <script> window.commentIdea = "#{@comment_id}" </script> When I am trying to use this variable (an example in del.coffee) $ -> console.log(commentIdea) nodeId = "comment/" + commentIdea I recieve an error(in console) SyntaxError: expected expression, got '<' <window class="commentIdea">173</window> Need some help on this |
Rails - return all values for nested-attributes, instead of just the 'pointer' Posted: 20 Aug 2016 12:31 AM PDT So, I've been banging my head against the wall for the past couple of hours trying to get this. Also, I'll change the name of the question when I know the name of the thing below. First question, what is this called? #<Comment:0x007fda3aaeb7c8> which is returned from the database. Secondly, I'm trying to return (render json) a comment that contains child comments. Something like this: [ { id: 1, title:'title', body:'body' }, { "#< Comment:0x007fda3b3517f0>": {}, "#< Comment:0x007fda3b3517f0>": {}, } ] How do I return the values of those comments? When I puts them in the console it shows their attributes and values, like so: puts comments[0][1] {#<Comment id: 17, body: "Another Reply Test", created_at: "2016-08-20 04:05:16", updated_at: "2016-08-20 04:05:16", parent_id: 13, user_id: 54>=>{}, #<Comment id: 18, body: "Another Reply Test", created_at: "2016-08-20 04:05:16", updated_at: "2016-08-20 04:05:16", parent_id: 13, user_id: 54>=>{}} but if I try to modify them at all - like to_a or to_json - it just blows up (for a lack of a better term) like such: puts comments[0][1].to_a #<Comment:0x007fda3b1911b8> {} #<Comment:0x007fda3b190fd8> {} I'm using Postgres, and I'm using closure_tree's hash_tree to sort the comments. Any advice would be very much appreciated, especially with the first question. EDIT: The def index that returns the comments: def index if request.headers["type"] == 'music' comments = Comment.where("song_id = ?", request.headers["id"]).hash_tree.to_a comments.each do |comment| puts comment[1] #shows all attributes and values puts comment[1].to_a #blows up puts comment[1].to_s #works end end if comments render json: {status:200, success:true, comments:comments} else render json: {status:404, success:false} end end |
My rendering in Rails (possibly) causes a 422 error Posted: 20 Aug 2016 08:19 AM PDT I have received reports from users to my website that they get Error 422 when visiting a "result" page using POST. I cannot re-create this error at all so I am wondering if there is anything in my code below that would cause this error in formatting? I expect there could be errors here since I have upgraded a Rails 3.x project to a Rails 4.2. I would either like to know if there is anything obvious in the code that would create 422 errors or if there is anyway to troubleshoot 422-errors. Basically, in #show there is a POST method to result. It is creating a result text and lands on a url like /this-post-name/result?r=abc123 . I am rendering #show in /result because it is basically loading the same page again but with a "result box". Having to use /result is a choice I made as a newbie programmer and is not absolutely necessary, I think. I am quite sure the error lies within the "respond_to" but can't figure that out, or troubleshoot it (i.e. re-create it). Also, I am not sure if this is important, but I get tons of AuthencityToken errors on this page. Edit: I managed to recreate this issue by accessing it through my iPhone and post a form, then I disabled cookies and send the form again. That would not be something people would do often but I guess having cookies disabled may cause this? def show @avaliable_posts = Post.where(:available => true) end def result if request.get? && params[:r].blank? # Just visiting /result withoutout POST or ?r url redirect_to category_path(@category) else set_round(session[:round_by_number]) # Either the visitor just posted the result or is revisiting through URL if !params[:r].blank? # Visitor arrived from URL @result = Result.find_by_scrambled_identifier(params[:r]) params_to_use = @result.params_used @params_to_use = @result.params_used else params_to_use = params @params_to_use = params_to_use end post_instance = @post.get_post_instance(params_to_use) if post_instance.valid? @post_result_array = post_instance.calculate_me(params_to_use) @post_result_text_array = @post_result_array[0] respond_to do |format| format.html { render :action => "show" } format.json { render :json => @post } end else # post not valid @errors = post_instance.errors respond_to do |format| format.html { render :action => "show" } format.xml { render :xml => @validator.errors, :status => :unprocessable_entity } format.json { render :json => @post } end end end end |
Javascript and Rails Filters and Sorting Posted: 19 Aug 2016 11:18 PM PDT I'm new to rails, and don't know much javascript. I have a model called "pieces", and piece has a genre , a title and a price . On my index page, I have buttons at the top that are supposed to filter the pieces by genre, and then sort those pieces by price increasing, price decreasing, or alphabetically by title. Note: right now, the genres can only be 'option1' and 'option2'. I have no idea how to do this. Thanks! Index.html.erb <div class="container"> <div class="center"> <h1>Listing Pieces</h1> </div> <!-- Sort and filter buttons start --> <div class="btn-group" role="group" aria-label="Filter and Sort"> <div class="btn-group" role="group"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Filter By Genre <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="#">option1</a></li> <li><a href="#">option2</a></li> </ul> </div> <div class="btn-group" role="group"> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Sort By <span class="caret"></span> </button> <ul class="dropdown-menu"> <li><a href="#">Price $-$$</a></li> <li><a href="#">Price $$-$</a></li> <li><a href="#">Title</a></li> </ul> </div> </div> <!-- Sort and filter buttons end --> <div id="pieces" class="transitions-enabled"> <% @pieces.each do |piece| %> <div class="box panel panel-default"> <%= link_to image_tag(piece.image.url(:medium)), piece %> <div class="panel-body"> <%= piece.title %><br/> <%= piece.genre %><br/> $<%= piece.price%> </div> </div> <% end %> </div> Also, not sure if this is relevant, but I am using jQuery masonry to animate the movement of the pieces. pieces.cofee $ -> $('#pieces').imagesLoaded -> $('#pieces').masonry itemSelector: '.box' isFitWidth: true |
Using Sidekiq For Active Job And Getting Activejob::Deserializationerror >>>>> Download Now
ReplyDelete>>>>> Download Full
Using Sidekiq For Active Job And Getting Activejob::Deserializationerror >>>>> Download LINK
>>>>> Download Now
Using Sidekiq For Active Job And Getting Activejob::Deserializationerror >>>>> Download Full
>>>>> Download LINK