How to reuse HTTP connection and share it between Sidekiq background jobs? Posted: 30 Nov 2016 08:18 AM PST My app sends multiple API requests and get responses in background jobs to third party server. For now every job opens new Http connection and closes it after receiving a response. If it's possible to share this connection between all my app's jobs? How to keep it alive while a pool of jobs is in progress? How to close it at the end? Thanks. |
How to destroy delayed jobs of particular queue? Posted: 30 Nov 2016 08:14 AM PST There is a Resque+Redis(and RoR of course) and a queue containing delayed jobs that I want to delete. I found is how to destroy certain queue that is active How to destroy jobs enqueued by resque workers? but it doesn't destroy delayed jobs of that queue |
Missing required keys after submitting form Posted: 30 Nov 2016 08:09 AM PST I have the form for creating new school in city which doesn't work on creating; it returns me an error with undefined parameter :id for city_path . <% if controller.action_name == "edit" %> <% if @school.errors.any? %> <div class="errors alert alert-danger"> <ul> <% @school.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <%= form_for @school, url: school_path(@school) do |f| %> <%= f.label "Ime:" %> <%= f.text_field :name, class: "form-control input-field" %> <%= f.label "URL slike:" %> <%= f.text_field :icon_url, class: "form-control input-field" %> <%= link_to school_path(@school), class: "btn btn-default", "data-no-turbolink": true do %> <i class="fa fa-chevron-left"></i> Nazad <% end %> <%= button_tag(type: "submit", class: "btn btn-default") do %> <i class="fa fa-check"></i> Pošalji <% end %> <% end %> <% else %> <% if @school.errors.any? %> <div class="errors"> <ul> <% @school.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <%= form_for @school, url: city_schools_path do |f| %> <%= f.label "Ime:" %> <%= f.text_field :name, class: "form-control input-field" %> <%= f.label "URL slike:" %> <%= f.text_field :icon_url, class: "form-control input-field" %> <%= link_to city_path(@city), class: "btn btn-default", "data-no-turbolink": true do %> <i class="fa fa-chevron-left"></i> Nazad <% end %> <%= button_tag(type: "submit", class: "btn btn-default") do %> <i class="fa fa-check"></i> Pošalji <% end %> <% end %> <% end %> When I try to send the form I get this error: No route matches {:action=>"show", :controller=>"cities", :id=>nil} missing required keys: [:id] This is my city_controller : class CitiesController < ApplicationController def index @cities = City.all end def show find_city @schools = @city.schools.all end def new @city = City.new end def edit find_city end def update find_city if @city.update(city_params) redirect_to city_path(@city) else render "edit" end end def create @city = City.new(city_params) if @city.save redirect_to index_path else render "new" end end private def find_city @city = City.find(params[:id]) end def find_schools @schools = @city.schools.all end def city_params params.require(:city).permit(:name, :icon_url) end end And this is school_controller : class SchoolsController < ApplicationController def index find_city @schools = @city.schools.all end def new find_city @school = @city.schools.new end def create find_city @school = @city.schools.new(school_params) if @school.save redirect_to school_path(@city, @school) else render "new" end end def show find_school @search = @school.users.ransack(params[:q]) @city = @school.city if (params.has_key?(:q)) @users = @search.result else # Prikazivanje svih korisnika koji su iste generacije kao i # poslednji dodati korisnik #@users = @school.users.where(generation: User.last.generation).order("sclass ASC") #@sclasses = @school.sclasses.where(generation: Sclass.last.generation).order("name ASC") if Sclass.last.nil? @sclasses = @school.sclasses.all else @sclasses = @school.sclasses.where(generation: Sclass.last.generation).order("name ASC") end end end def edit find_school end def update find_school if @school.update(school_params) redirect_to school_path(@school) else render "edit" end end def destroy find_city find_school @school.destroy redirect_to city_path(@city) end private def find_city @city = City.find(params[:city_id]) end def find_school @school = School.find(params[:id]) end def school_params params.require(:school).permit(:name, :icon_url) end end Here is the school show view: <% title "#{@school.name}" %> <div class="row"> <div class="col-md-12 text-center city-title"> <h3><%= @school.name %></h3> </div> </div> <%= search_form_for @search, url: school_path(@school) do |f| %> <div class="row input-field"> <div class="text-center"> <%= f.text_field :full_name_cont, placeholder: "Pretraga učenika" %> </div> </div> <div class="row input-field"> <div class="text-center"> <%= f.select :generation_eq, options_from_collection_for_select(@school.users.order("generation DESC").select(:generation).uniq, "generation", "generation", @search.generation_eq), {}, { :class => "selectpicker" } %> </div> </div> <div class="row input-field"> <div class="text-center"> <%= f.submit "Traži", class: "btn btn-default" %> </div> </div> <% end %> <div class="container"> <div class="row"> <div class="col-md-12"> <%= link_to city_path(@school.city), class: "btn btn-default" do %> <i class="fa fa-chevron-left"></i> Nazad--> <% end %> <% if is_admin? %> <%= link_to edit_school_path(@school), class: "btn btn-default" do %> <i class="fa fa-pencil"></i> Uredi školu <% end %> <%= link_to new_school_sclass_path(@school), class: "btn btn-default" do %> <i class="fa fa-plus"></i> Dodaj razred <% end %> <%= link_to new_school_generation_picture_path(@school), class: "btn btn-default" do %> <i class="fa fa-plus"></i> Dodaj tablo <% end %> <% end %> </div> </div> </div> <div class="container"> <div class="users"> <% if !@users.nil? %> <% @users.in_groups_of(4, false).each do |users| %> <div class="row"> <% users.each do |user| %> <div class="col-xs-6 col-md-3 text-center"> <a href="<%= user_path(@city, @school, user.sclass, user) %>" class="thumbnail school" data-no-turbolink="true"> <%= image_tag user.avatar.url(:thumb), size: "100", class: "user-profile-image img-responsive" %> <%= user.full_name %> <br/> <span class="badge"> <%= show_user_class(user.sclass.name) %> </span> </a> </div> <% end %> </div> <% end %> <% else %> <% @sclasses.in_groups_of(4, false).each do |sclasses| %> <div class="row"> <% sclasses.each do |sclass| %> <div class="col-xs-6 col-md-3 text-center"> <a href="<%= sclass_path(sclass) %>" class="thumbnail school" data-no-turbolink="true"> <%= image_tag sclass.icon_url, class: "img-responsive" %> <%= show_user_class(sclass.name) %> </a> </div> <% end %> </div> <% end %> <% end %> </div> </div> Routes: Prefix Verb URI Pattern Controller#Action root GET / welcome#index index GET /pocetna(.:format) welcome#index new_cart GET /korpa(.:format) carts#new success GET /poslato(.:format) carts#success sessions POST /sessions(.:format) sessions#create new_session GET /sessions/new(.:format) sessions#new session DELETE /sessions/:id(.:format) sessions#destroy login GET /prijava(.:format) sessions#new prijava POST /prijava(.:format) sessions#create logout GET /odjava(.:format) sessions#destroy odjava DELETE /odjava(.:format) sessions#destroy school_sclasses GET /skola/:school_id/razred(.:format) sclasses#index POST /skola/:school_id/razred(.:format) sclasses#create new_school_sclass GET /skola/:school_id/razred/dodaj(.:format) sclasses#new edit_sclass GET /razred/:id/uredi(.:format) sclasses#edit sclass GET /razred/:id(.:format) sclasses#show PATCH /razred/:id(.:format) sclasses#update PUT /razred/:id(.:format) sclasses#update school_users GET /skola/:school_id/ucenik(.:format) users#index POST /skola/:school_id/ucenik(.:format) users#create new_school_user GET /skola/:school_id/ucenik/dodaj(.:format) users#new edit_user GET /ucenik/:id/uredi(.:format) users#edit user GET /ucenik/:id(.:format) users#show PATCH /ucenik/:id(.:format) users#update PUT /ucenik/:id(.:format) users#update DELETE /ucenik/:id(.:format) users#destroy school_generation_pictures POST /skola/:school_id/tablo(.:format) generation_pictures#create new_school_generation_picture GET /skola/:school_id/tablo/novi(.:format) generation_pictures#new edit_generation_picture GET /tablo/:id/uredi(.:format) generation_pictures#edit generation_picture GET /tablo/:id(.:format) generation_pictures#show PATCH /tablo/:id(.:format) generation_pictures#update PUT /tablo/:id(.:format) generation_pictures#update city_schools POST /gradovi/:city_id/skola(.:format) schools#create new_city_school GET /gradovi/:city_id/skola/nova-skola(.:format) schools#new edit_school GET /skola/:id/uredi(.:format) schools#edit school GET /skola/:id(.:format) schools#show PATCH /skola/:id(.:format) schools#update PUT /skola/:id(.:format) schools#update cities POST /gradovi(.:format) cities#create new_city GET /gradovi/novi(.:format) cities#new edit_city GET /gradovi/:id/uredi(.:format) cities#edit city GET /gradovi/:id(.:format) cities#show PATCH /gradovi/:id(.:format) cities#update PUT /gradovi/:id(.:format) cities#update carts GET /carts(.:format) carts#index POST /carts(.:format) carts#create edit_cart GET /carts/:id/edit(.:format) carts#edit cart GET /carts/:id(.:format) carts#show PATCH /carts/:id(.:format) carts#update PUT /carts/:id(.:format) carts#update DELETE /carts/:id(.:format) Also, form is submitting :id and :format parameters forming weird URL (http://localhost:3000/skola/1.17). |
How do I install an existing rails app alongside a WAMP server? Posted: 30 Nov 2016 08:07 AM PST I am working on making a website and need to install rails alongside WAMP everything I have found is to install a new rails app i need to install an existing rails application alongside a WAMP server. Anyone know how to do that? |
active record query order where first Posted: 30 Nov 2016 08:22 AM PST I am using c9 cloud ruby on rails and rails version is 5.0.0.1 I want to use active record query to select best rating restaurant and not have been visited yesterday. When I applied all where, order and first syntax in the query, it pops up error and but if I don't put where or don't use order, it works fine: This works: restaurant1= Restaurant.order('rating').last! @suggested_restaurants=restaurant1.name This gives strange results: restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday} @suggested_restaurants=restaurant1 results: #<ActiveRecord::QueryMethods::WhereChain:0x000000046af7f8> This triggered error: restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}.last @suggested_restaurants=restaurant1 error: undefined method last' for #ActiveRecord::QueryMethods::WhereChain:0x00000004587a10>` I can get around this issue by find_by_sql but really wants to know why and how to use "where" in rails 5. Thanks a lot!! |
simple_form devise ActionView::Template::Error (wrong number of arguments (1, 0)) Posted: 30 Nov 2016 07:49 AM PST I have upgraded rails to 5.0.0.1 and ruby 2.3.0 now I'm getting following error in my devise view using simple_form ActionView::Template::Error (wrong number of arguments (given 1, expected 0)): at this line of code <%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => 'form-horizontal' }) do |f| %> I have googled this for hours and cannot find any solution, my devise version is 4.2.0 and simple_form 3.3.1 |
Custom headers missing on production Rails site Posted: 30 Nov 2016 07:48 AM PST I've built an API that uses token-based auth and it's working fine on my local dev environment, using Puma. However, I've just deployed it onto a Nginx/Puma stack and noticed that custom headers are going missing. When my header is called Authorization , it's not available within the app. However, if I call it X-Authorization then it works as expected. Of course, I can just use the X- format but I'm curious as to why it's being filtered out and to whether it's Nginx, Puma or something else entirely that is doing it. My Nginx config contains the following: location @app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://{{ app_name }}; } I'm also using the rack-cors gem, set up as follows: config.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :delete, :put, :patch, :options, :head] end end |
Query a JSONB column from a has_many :through relations Posted: 30 Nov 2016 07:30 AM PST Hi I am trying to do a query on a JSONB column from a has_many :through association. class App has_many: events, through: :event_types end class EventType has_many :events, dependent: :destroy end class Event belongs_to :event_type end Event model has a jsonb column name 'properties' app.events will return Event::ActiveRecord_Associations_CollectionProxy not ActiveRecord Relations I have an Event as such: #<Event:0x007fc91a8bc0c8 id: 21, created_at: Wed, 02 Nov 2016 02:21:59 UTC +00:00, updated_at: Wed, 02 Nov 2016 02:21:59 UTC +00:00, properties: {"123"=>true, "browsed"=>false}, event_type_id: 120, app_device_manifest_id: 1106> if I try to Query it this way. it returns an empty Event::ActiveRecord_Associations_CollectionProxy app.events.where("properties ->> 'browsed' = ?", "false") #<Event::ActiveRecord_AssociationRelation:0x3fe48cdaf740> I don't want to do things like pluck ids out of the app.events and map it to Event.where query. What would be the best way to get at the events that an app has? |
Rails query through multiple models Posted: 30 Nov 2016 07:49 AM PST It's been 2 days by now that I'm struggling to write query. So, I'm trying to query within these 3 related models: class Company... has_many :programs end class Program... belongs_to :company has_many :transactions end class Transaction... belongs_to :program end As output, I need a list of the amount of all Transactions each Company made and on what date. |
Upload an attachment to S3 using AWS SDK 2 Posted: 30 Nov 2016 07:16 AM PST I am using aws-sdk-rails gem over rails 5.0.0.1. I followed these guides I am new in RoR so I am getting this error This is my contents_controller.rb file def create s3 = Aws::S3::Resource.new(region: 'us-west-2') file = content_params[:attachment] puts file.path.split('/').last obj = s3.bucket(INPUT_BUCKET).object(file) obj.upload_file(file.path.split('/').last) @content = Content.new(content_params) if @content.save redirect_to contents_path, notice: "The content #{@content.name} has been uploaded." else render "new" end end Do you recommend me using a gem to handle these tasks? In that case, which one? |
Disable ruby on rails job for test Posted: 30 Nov 2016 07:21 AM PST I'm writing controller test with rspec and after action completed, my job supposed to send email to the admin user. But I'd like to disable this job for my tests or mock it somehow. How can I do this? I'm using delayed_job_active_record+daemons gem. class AdminNotificationJob < ActiveJob::Base queue_as :default def perform(method, parameter) User.admin.includes(:profile).each do |admin| AdminMailer.send(method, admin, parameter).deliver_later end end end |
Having different rails and gems versions installed on dev environment Posted: 30 Nov 2016 07:08 AM PST I'm quite newbie in ruby and ruby on rails and I'd like some clarification, if possible. I'm currently having rails 4.2.6 installed on my development environment in which I have built a few projects. Now, for my new projects I'd like to use Rails 5, so I assume that if I type the gem install rails command will get me the latest rails verion and probably set it as default, so every time I want to create a new project by rails new my_new_project_name this project will have the latest version (currently v5). My question is will my gem list contain both rails versions then or is it going to cause any conflicts and issues to my old porjects? so, if I want to work back on any of my projects which has the "old" version, won't affect of any changes, right? As far as I understand its the bundler who picks the version of each gem, right? If thats the case, I assume same thing applies and for every other gem that I use for each project, right? |
Encrypt Ruby code inside a gem Posted: 30 Nov 2016 07:06 AM PST I want to ship out a gem to on premises for clients. I don't want them to know my code so I want to encrypt or obfuscate code inside the .gem file and ship it to them to integrate inside their ruby projects. Any ref? |
LoadError: cannot load such file -- rvm/capistrano Posted: 30 Nov 2016 07:17 AM PST I want deploy sinatra project. Run command cap production deploy . errors: cap aborted! LoadError: cannot load such file -- rvm/capistrano config/deploy.rb:1:in `require' config/deploy.rb:1:in `<top (required)>' /home/user/.rbenv/versions/2.3.1/bin/cap:23:in `load' /home/user/.rbenv/versions/2.3.1/bin/cap:23:in `<top (required)>' /home/user/.rbenv/versions/2.3.1/bin/bundle:23:in `load' /home/user/.rbenv/versions/2.3.1/bin/bundle:23:in `<main>' #gemfile source 'http://rubygems.org' gem "rake" gem "sinatra" gem "sinatra-activerecord" gem "sinatra-flash" gem "pg" gem "bcrypt" gem "pry" gem "pony" gem "capistrano", '~> 3.1.0' gem "capistrano-bundler", '~> 1.1.2' gem "capistrano-rvm", github: "capistrano/rvm" Setting capistrano Capgile file Capfile # Load DSL and set up stages require 'capistrano/setup' # Include default deployment tasks require 'capistrano/deploy' # If you are using rvm add these lines: require 'capistrano/rvm' set :rvm_type, :user set :rvm_ruby_version, '2.3.1-p112' #Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r } In deploy file i added folowing settng for rvm #config/deploy.rb #RVM and bundler settings set :bundle_cmd, "/home/deploy/.rvm/gems/ruby-2.3.1-p112@global/bin/bundle" set :bundle_dir, "/home/deploy/.rvm/gems/ruby-2.3.1-p112/gems" set :rvm_ruby_string, :local set :rack_env, :production I dont undestand why this error, maybe becose First time on local I used rbenv for installing ruby and bundle install gems. But after installed rvm, in directory project select right version ruby with command rvm use 2.3.1. ruby -v ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux] How solve this issue? Thank you for advance. |
Where to implement a Linked List Stack in Rails app Posted: 30 Nov 2016 08:18 AM PST I am trying to implement a Linked List Stack in my Rails app which is a basic to-do list. But I am not sure where I would place the code for the Linked List within the current Rails App structure. Can someone offer any guidance? Would this go within the Model or the Controller? Screenshot of Basic to do list app Tasks Controller: class TasksController < ApplicationController def create @task = current_user.tasks.build(task_params) if @task.save flash[:notice] = "Task created successfully" else flash[:error] = "Error creating task" end redirect_to current_user end def destroy @task = current_user.tasks.find(params[:id]) if @task.destroy flash[:notice] = "Task completed successfully" else flash[:error] = "Error completing task" end redirect_to current_user end private def task_params params.require(:task).permit(:name) end Show.html.erb file for the tasks created <h1>Hello, <%= current_user.email %></h1> <h2>Create New Task</h2> <%= form_for [current_user, @task] do |f| %> <%= f.label :name %> <%= f.text_field :name %> <%= f.submit "Create", class: 'btn btn-primary' %> <% end %> <h2>Current Tasks</h2> <% current_user.tasks.each do | task| %> <p> <%= task.name %> <%=link_to [current_user, task], method: :delete do %> <span class="glyphicon glyphicon-ok"></span> <% end %> </p> <% end %> Task.rb(Model) class Task < ActiveRecord::Base belongs_to :user end User.rb(Model) class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable has_many :tasks devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end The Linkedlist Stack I would like to implement in the Rails App module LinkedList class Node attr_accessor :value, :next_node def initialize(value, next_node) @value = value @next_node = next_node end end class Stack def initialize @first = nil end def push(value) @first = Node.new(value, @first) end def pop flash[:notice] = "Task completed successfully" if is_empty? value = @first.value @first = @first.next_node value end def is_empty? @first.nil? end end end |
How do I add a custom predicate-builder in Rails 5? Posted: 30 Nov 2016 06:37 AM PST In Rails 4, If I had an ArrayLikeClass class and I wanted to use its objects in where queries like Model.where(id: instance_of_array_like_class) , I could do so by registering a predicate-builder: ActiveRecord::PredicateBuilder.register_handler(ArrayLikeClass, ActiveRecord::PredicateBuilder::ArrayHandler.new) after which instances of ArrayLikeClass would behave same as instances of Array when used in where queries. However, with Rails 5, the API is changed and ActiveRecord::PredicateBuilder::ArrayHandler.new now requires an instance of ActiveRecord::PredicateBuilder . Also register_handler is now an instance method in ActiveRecord::PredicateBuilder . So, how can I register a predicate-builder handler in Rails 5 for a custom class? |
Filterring ActiveRecord Relation...if there are no matches. (Null the active record relation) Posted: 30 Nov 2016 06:35 AM PST I have a dashboard that allows for filtering of the results by different parameters. I build methods to filter the results by the given criteria. One area where I'm having trouble is if the previous line should null out the active record relation. Should I just put a bunch of if present? stat def find_website_stats(options = {}) if options[:date_between].present? start_date = options[:date_between].split(/-/).first.to_date end_date = options[:date_between].split(/-/).last.to_date + 1 elsif options[:start_date].present? start_date = options[:start_date].to_date end_date = options[:end_date].to_date + 1 if options[:end_date].present? end contractor_name = options[:search_contractor] if options[:search_contractor].present? distributor_name = options[:search_distributor] if options[:search_distributor].present? distributor_ids = options[:with_distributor] if options[:with_distributor].present? contractor_ids = options[:with_contractor] if options[:with_contractor].present? with_country = options[:with_country] if options[:with_country].present? with_state = options[:with_state] if options[:with_state].present? search_city = options[:search_city] if options[:search_city].present? web_stats = self.website_stats if web_stats.present? web_stats = web_stats.where(contractor_id: [*contractor_ids]) if contractor_ids.present? if distributor_ids.present? web_stat_ids = DistributorWebsiteStat.where(distributor_id: [*distributor_ids]).pluck(:website_stat_id) web_stats = web_stats.where(id: [*web_stat_ids]) end web_stats = web_stats.where(date_recorded: start_date..end_date) if start_date.present? && end_date.present? web_stats = web_stats.with_country(with_country) if with_country.present? web_stats = web_stats.with_state(with_state) if with_state.present? web_stats = web_stats.search_city(search_city) if search_city.present? #untested if contractor_name.present? searched_contractor_ids = Brand.search_contractor(contractor_name).pluck(:id) web_stats = web_stats.where(contractor_id: [*searched_contractor_ids]) end if distributor_name.present? searched_distributor_ids = Brand.search_distributor(distributor_name).pluck(:id) web_stat_ids = DistributorWebsiteStat.where(distributor_id: [*searched_distributor_ids]) web_stats = web_stats.where(id: [*web_stat_ids]) end
|
Hello Admin,
ReplyDeleteI need to utilize dynamic record inquiry to choose best appraising eatery and not have been visited yesterday. At the point when I applied all where, request and first grammar in the inquiry, it springs up mistake and yet on the off chance that I don't put where or don't utilize request.
Regards,
Thanks
RITU