How to get data out of an $.ajax() call [duplicate] Posted: 02 Dec 2016 07:36 AM PST This question already has an answer here: I am attempting to get a variable from a ruby on rails controller using javascript. I am able to get the data from the controller into my console but I cannot use the variables outside of the functions that get the data. My code: function get_location_calc_level_data(useReturnData) { $.ajax({ method: "GET", url: "/st_location_mgmt/inventory/get_location_calc_level", success: function(data) { useReturnData(data); } }); } var level; get_location_calc_level_data(function(output){ console.log("output: ", output); console.log("output level: ", output.level); level = output; }); var levels = level; console.log("level: ",level) console.log("levels: ",levels) The console calls return: 2016-12-02 10:27:20.498 VM16344:100 level: undefined 2016-12-02 10:27:20.499 VM16344:101 levels: undefined 2016-12-02 10:27:20.593 VM16344:94 output: Object {level: "full"} 2016-12-02 10:27:20.596 VM16344:95 output level: full My goal is to use that "level" variable to be used as a flag that will drive behavior in another function $.each() that is called after this code |
Sidekiq and unqueueing in ruby Posted: 02 Dec 2016 07:05 AM PST I am currently enabling queueing in on of my app wrote in Ruby. I use sidekiq and have define a worker class as below: class Worker include Sidekiq::Worker def perform(params) sleep 10 @@logger.info("--------------------------") @@logger.info("Request received") @@logger.info("--------------------------") end end I am calling it from my main entry point called 'api.rb' post '/receive/?' do @@logger.debug("/retrieve endpoint received") Worker.perform_async @params end this working fine and each time the sleep is done, the next queued task is started. In my case, I need to unqueued or start the next item queued only when I decide it. it will be triggered by an external event. in my 'api.rb', I have added: post '/response/?' do next_task end The way the code works is that '/receive' can queued 10 requests. the first request will triggered a specific action (sent a post command to a server). I expect the remote server to send me back a request through '/response' to tell me that the action is finished. when this response is received, I use the 'next_task' api to remove the previous task which was running and now completed and move to the next queued one. Any idea, how to create a custom trigger to unqueue and start the new job. Is there SIGNAL which allow me to avoid the sidekiq framework to unqueue until I send a specific signal. Merci |
Rails Precompile Assets Error on Local Posted: 02 Dec 2016 07:06 AM PST Trying to precompile assets on my my local machine. I keep getting the following error. How can I fix this? -ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16] - Rails 5.0.0.1 rake assets:precompile production --trace ** Invoke assets:precompile (first_time) ** Invoke assets:environment (first_time) ** Execute assets:environment ** Invoke environment (first_time) ** Execute environment ** Execute assets:precompile rake aborted! Don't know how to build task 'production' (see --tasks) /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/task_manager.rb:71:in `[]' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:151:in `invoke_task' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:108:in `block (2 levels) in top_level' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:108:in `each' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:108:in `block in top_level' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:117:in `run_with_threads' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:102:in `top_level' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:80:in `block in run' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:178:in `standard_exception_handling' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/lib/rake/application.rb:77:in `run' /usr/local/rvm/gems/ruby-2.3.1/gems/rake-11.3.0/exe/rake:27:in `<top (required)>' /usr/local/rvm/gems/ruby-2.3.1/bin/rake:23:in `load' /usr/local/rvm/gems/ruby-2.3.1/bin/rake:23:in `<main>' |
Elasticsearch + Tire: how to search blank value in string column Posted: 02 Dec 2016 06:51 AM PST I am using elasticsearch with tire(0.6.2) gem in my rails(3.2.22) project. users table having a string column named 'active_code'. I can't able to search with empty string in active_code column. I tried following samples but i couldn't get. tire.search(load: true, page: params[:page], per_page: 15) do query do boolean do must { string params[:query], default_operator: "AND" } if params[:query].present? must { term :active_code, '' } end #boolean# end #query end How to resolve this problem? Thank you. |
wicked_pdf only partially uses bootstrap Posted: 02 Dec 2016 06:49 AM PST I'm generating a PDF in Rails using wicked_pdf. I've followed instructions on their wiki about how to include Bootstrap but with only partial success. I've also seen answers on here, but also without perfect results. In debug mode, everything looks fine. But the PDF is missing background colours using helpers like .bg-danger and striped tables. However I have got the correct typography, layout/column helpers and things like .img-responsive. Also, the page numbers don't work; I'm not sure if that's related or not. controller extract respond_to do |format| format.html do render :template => "report/report.html" end format.pdf do render pdf: "report", template: 'report/report.html', layout: 'pdf', show_as_html: params[:debug].present?, footer: { right: '[page] of [topage]' }, javascript_delay: 2000, page_size: 'A4', viewport_size: '1280x1024' layouts/pdf.html.haml %html %head %meta{ 'content' => 'text/html; charset=UTF-8', 'http-equiv'=> 'content-type' } = wicked_pdf_stylesheet_link_tag "pdf", media: "all" = wicked_pdf_javascript_include_tag "chartkick" = wicked_pdf_javascript_include_tag "number_pages" %body = yield pdf.sass @import "helpers" @import "font-awesome" @import "bootstrap-sprockets" @import "bootstrap" @import "bootstrap/variables" @import "bootstrap/mixins" @include make-grid(sm) @include make-grid(md) @include make-grid(lg) body background-color: white .page-break display: block clear: both page-break-after: always page-break: always |
Can't save nested attributes in rails 5 Posted: 02 Dec 2016 07:19 AM PST I have two model: 1.Personne class Personne < ApplicationRecord has_one :proprietaire accepts_nested_attributes_for :proprietaire validates :nom, :prenom, :tel, :email, presence: true end 2 Proprietaire
class Proprietaire < ApplicationRecord belongs_to :personne validates :commune_id, :quartier, presence: true end the Controller is: class PersonneController < ApplicationController def display_proprietaires @proprietaires = Personne.all #@proprietaires = @proprietaires.proprietaire end def new_proprietaire @provinces = Province.where(:parentId => nil) @communes = Province.where.not(:parentId => nil) @personne = Personne.new @personne.build_proprietaire end def create_proprietaire @proprietaire = Personne.new(proprietaire_params) @proprietaire.build_proprietaire respond_to do |format| if @proprietaire.save flash[:notice] = "succes" flash[:type] = "success" format.html { redirect_to action: :display_proprietaires } else flash[:notice] = "fail" flash[:type] = "warning" format.html { redirect_to action: :display_proprietaires } end end end def proprietaire_params params.require(:personne).permit(:nom, :prenom, :tel, :email, proprietaire_attributes: [:id, :commune_id, :quartier]).except(:province, :commit) end end the View is: <%= form_for @personne, :url => url_for(:controller=>'personne', :action=>'create_proprietaire' ) do |f| %> <div class="row"> <div class="col-xs-6 col-sm-6 col-lg-6"> <div class="form-group"> <%= f.label(:nom, 'Nom : ') %> <%= f.text_field :nom, {class: "form-control", placeholder: 'Nom'} %> </div> <div class="form-group"> <%= f.label(:prenom, 'Prenom : ')%> <%= f.text_field :prenom, {class: "form-control", placeholder: "Prenom"} %> </div> <div class="form-group"> <%= f.label(:tel, 'Telephone : ')%> <%= f.text_field :tel, {class: "form-control", placeholder: "Telephone"} %> </div> <div class="form-group"> <%= f.label(:email, 'Email : ') %> <%= f.text_field :email, {class: "form-control", placeholder: "Email"} %> </div> <div class="form-group"> <%= label_tag(:province, 'Province : ') %> <%= select_tag(:province, options_for_select(@provinces.collect{|value| [value.denomination, value.id]}), {class: "form-control", id: "province", remote: true} ) %> </div> <%= f.fields_for :proprietaire do |proprio| %> <div class="form-group"> <%= proprio.label(:commune_id, 'Commune : ') %> <%= proprio.select :commune_id, options_for_select(@communes.collect{|value| [value.denomination, value.id]}),{}, {class: "form-control", id: "commune"} %> </div> <div class="form-group"> <%= proprio.label :quartier, "Quartier" %> <%= proprio.text_field :quartier, {class: "form-control", placeholder: "Quartier"} %> </div> <% end %> <%= f.submit "Enregistre", {class: 'btn btn-info'} %> <% end %> Routes:
resources :personne do collection do post :create_proprietaire get :display_proprietaires get :new_proprietaire end end I'm new in RoR, When I try to save nothing happens, I'm getting this: Could someone helps me on this. Thank you! |
Not working database_cleaner with Rspec test Posted: 02 Dec 2016 06:43 AM PST Hello guys I'm trying to set up database_cleaner, but I can't do that and i don't know what I'm missing. What i have up to now: users_controller_spec require 'rails_helper' describe UsersController, :type => :controller do #user = User.create!(email: "test@test.com", password: "123456") user = FactoryGirl.create(:user) describe 'GET #show' do context 'User is logged in' do before do sign_in user end it 'loads correct user details' do get :show, id: user.id expect(response).to have_http_status(200) expect(assigns(:user)).to eq user end end context 'No user is logged in' do it 'redirects to login' do get :show, id: user.id expect(response).to redirect_to(new_user_session_path) end end end end support/database_cleaner.rb RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.clean_with(:truncation) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, :js => true) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end rails_helper.rb have line config.use_transactional_fixtures = false and uncommented line Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f } Terminal log /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/validations.rb:78:in `raise_validation_error': Validation failed: Email has already been taken (ActiveRecord::RecordInvalid) from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/validations.rb:50:in `save!' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/attribute_methods/dirty.rb:30:in `save!' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/transactions.rb:324:in `block in save!' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/transactions.rb:395:in `block in with_transaction_returning_status' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/abstract/database_statements.rb:232:in `block in transaction' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/abstract/transaction.rb:189:in `within_new_transaction' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/connection_adapters/abstract/database_statements.rb:232:in `transaction' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/transactions.rb:211:in `transaction' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/transactions.rb:392:in `with_transaction_returning_status' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/transactions.rb:324:in `save!' from /var/lib/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/suppressor.rb:45:in `save!' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/configuration.rb:18:in `block in initialize' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/evaluation.rb:15:in `create' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/strategy/create.rb:12:in `block in result' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/strategy/create.rb:9:in `tap' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/strategy/create.rb:9:in `result' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/factory.rb:42:in `run' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/factory_runner.rb:29:in `block in run' from /var/lib/gems/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/notifications.rb:166:in `instrument' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/factory_runner.rb:28:in `run' from /var/lib/gems/2.3.0/gems/factory_girl-4.7.0/lib/factory_girl/strategy_syntax_method_registrar.rb:20:in `block in define_singular_strategy_method' from /home/kristis/Desktop/myapp/spec/controllers/users_controller_spec.rb:7:in `block in <top (required)>' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/example_group.rb:385:in `module_exec' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/example_group.rb:385:in `subclass' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/example_group.rb:258:in `block in define_example_group_method' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/dsl.rb:43:in `block in expose_example_group_alias' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/dsl.rb:84:in `block (2 levels) in expose_example_group_alias_globally' from /home/kristis/Desktop/myapp/spec/controllers/users_controller_spec.rb:3:in `<top (required)>' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `block in load_spec_files' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `each' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `load_spec_files' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:100:in `setup' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:86:in `run' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:71:in `run' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:45:in `invoke' from /var/lib/gems/2.3.0/gems/rspec-core-3.5.4/exe/rspec:4:in `<top (required)>' from /usr/local/bin/rspec:23:in `load' from /usr/local/bin/rspec:23:in `<main>' Thank you for help! |
Rails Active Record cancel save or create in before_create without raising exception Posted: 02 Dec 2016 06:44 AM PST Actually, I want to test a model callback. system_details.rb (Model) class SystemDetail < ActiveRecord::Base belongs_to :user attr_accessible :user_agent before_create :prevent_if_same def agent Browser.new(ua: user_agent, accept_language: 'en-us') end def prevent_if_same rec = user.system_details.order('updated_at desc').first return true unless rec if rec.user_agent == user_agent rec.touch return false end end end prevent_if_same method is working fine and working as expected but it raises exception ActiveRecord::RecordNotSaved when it returns false, and the exception breaks the rspec test .what I want is, It should silently cancel save without raising an exception. system_detail_spec.rb (rspec) require 'rails_helper' RSpec.describe SystemDetail, :type => :model do context '#agent' do it 'Checks browser instance' do expect(SystemDetail.new.agent).to be_an_instance_of(Browser) end end context '#callback' do it 'Ensure not creating consecutive duplicate records' do user = create :end_user system_detail = create :system_detail, :similar_agent, user_id: user.id updated_at = system_detail.updated_at system_detail2 = create :system_detail, :similar_agent, user_id: user.id system_detail.reload expect(system_detail2.id).to be_nil expect(system_detail.updated_at).to be > updated_at end end end The 2nd test #callback was failing because of exception. Failures: 1) SystemDetail#callback ensure not creating duplicate records Failure/Error: system_detail2 = create :system_detail, :similar_agent, user_id: user.id ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved Is there any way to silently cancel save without raising an exception? |
Find the matching result by postgresql query Posted: 02 Dec 2016 06:42 AM PST I have an issue to get results based on selection in dropdown. I have dropdown with categories. I have three table with associated to each other. Class User has_and_belongs_to_many :categories end Class Category has_and_belongs_to_many :categories end I have generated migration with join table "categories_users" and it has foreign key of both table. we have to select categories should be matched with users that have those selected categories only. Now I need to find the result based on above things. Please help me to fix this issue. |
How to remove square brackets and commas from array Posted: 02 Dec 2016 06:26 AM PST i'm creating tooltip for Likes. Here's an images which I'm passing to tooltip: - images = bonus.like_user_avatars.map {|src| "<img src='#{src}'>" } bonus.like_user_avatar is ready collection of liked user's avatar. Everything works fine, but it look like this I need to remove the square brackets and commas, I just want only the avatars in tooltip. How can I do it? UPDATE: tooltip code: span.has-tip data-tooltip="" data-template="<div class='tooltip'>#{images}</div>"Like |
Error when launch Rails application Posted: 02 Dec 2016 05:33 AM PST I have Rails application, which was not written by me. I am not Rails developer, so before I dig into the code I will be thankful if you look at stack trace. May be it is some standard problem: Started GET "/" for 127.0.0.1 at 2016-12-02 16:14:20 +0300 Processing by ProjectsController#index as HTML Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms) RuntimeError (): <compiled>:1:in `<compiled>' <compiled>:71:in `eval' <compiled>:71:in `block (2 levels) in <compiled>' activesupport (4.2.5) lib/active_support/callbacks.rb:446:in `instance_exec' activesupport (4.2.5) lib/active_support/callbacks.rb:446:in `block in make_lambda' activesupport (4.2.5) lib/active_support/callbacks.rb:164:in `block in halting' activesupport (4.2.5) lib/active_support/callbacks.rb:504:in `block in call' activesupport (4.2.5) lib/active_support/callbacks.rb:504:in `each' activesupport (4.2.5) lib/active_support/callbacks.rb:504:in `call' activesupport (4.2.5) lib/active_support/callbacks.rb:92:in `__run_callbacks__' activesupport (4.2.5) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks' activesupport (4.2.5) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (4.2.5) lib/abstract_controller/callbacks.rb:19:in `process_action' actionpack (4.2.5) lib/action_controller/metal/rescue.rb:29:in `process_action' actionpack (4.2.5) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' activesupport (4.2.5) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (4.2.5) lib/active_support/notifications/instrumenter.rb:20:in `instrument' activesupport (4.2.5) lib/active_support/notifications.rb:164:in `instrument' actionpack (4.2.5) lib/action_controller/metal/instrumentation.rb:30:in `process_action' actionpack (4.2.5) lib/action_controller/metal/params_wrapper.rb:250:in `process_action' activerecord (4.2.5) lib/active_record/railties/controller_runtime.rb:18:in `process_action' actionpack (4.2.5) lib/abstract_controller/base.rb:137:in `process' actionview (4.2.5) lib/action_view/rendering.rb:30:in `process' actionpack (4.2.5) lib/action_controller/metal.rb:196:in `dispatch' actionpack (4.2.5) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch' actionpack (4.2.5) lib/action_controller/metal.rb:237:in `block in action' actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:76:in `dispatch' actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:45:in `serve' actionpack (4.2.5) lib/action_dispatch/journey/router.rb:43:in `block in serve' actionpack (4.2.5) lib/action_dispatch/journey/router.rb:30:in `each' actionpack (4.2.5) lib/action_dispatch/journey/router.rb:30:in `serve' actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:817:in `call' rack (1.6.4) lib/rack/etag.rb:24:in `call' rack (1.6.4) lib/rack/conditionalget.rb:25:in `call' rack (1.6.4) lib/rack/head.rb:13:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/params_parser.rb:27:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/flash.rb:260:in `call' rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context' rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/cookies.rb:560:in `call' activerecord (4.2.5) lib/active_record/query_cache.rb:36:in `call' activerecord (4.2.5) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' activesupport (4.2.5) lib/active_support/callbacks.rb:88:in `__run_callbacks__' activesupport (4.2.5) lib/active_support/callbacks.rb:778:in `_run_call_callbacks' activesupport (4.2.5) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (4.2.5) lib/action_dispatch/middleware/callbacks.rb:27:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/reloader.rb:73:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/remote_ip.rb:78:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.2.5) lib/rails/rack/logger.rb:38:in `call_app' railties (4.2.5) lib/rails/rack/logger.rb:20:in `block in call' activesupport (4.2.5) lib/active_support/tagged_logging.rb:68:in `block in tagged' activesupport (4.2.5) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (4.2.5) lib/active_support/tagged_logging.rb:68:in `tagged' railties (4.2.5) lib/rails/rack/logger.rb:20:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/request_id.rb:21:in `call' rack (1.6.4) lib/rack/methodoverride.rb:22:in `call' rack (1.6.4) lib/rack/runtime.rb:18:in `call' activesupport (4.2.5) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' rack (1.6.4) lib/rack/lock.rb:17:in `call' actionpack (4.2.5) lib/action_dispatch/middleware/static.rb:116:in `call' rack (1.6.4) lib/rack/sendfile.rb:113:in `call' railties (4.2.5) lib/rails/engine.rb:518:in `call' railties (4.2.5) lib/rails/application.rb:165:in `call' rack (1.6.4) lib/rack/content_length.rb:15:in `call' thin (1.6.4) lib/thin/connection.rb:86:in `block in pre_process' thin (1.6.4) lib/thin/connection.rb:84:in `catch' thin (1.6.4) lib/thin/connection.rb:84:in `pre_process' thin (1.6.4) lib/thin/connection.rb:53:in `process' thin (1.6.4) lib/thin/connection.rb:39:in `receive_data' eventmachine (1.0.8) lib/eventmachine.rb:193:in `run_machine' eventmachine (1.0.8) lib/eventmachine.rb:193:in `run' thin (1.6.4) lib/thin/backends/base.rb:73:in `start' thin (1.6.4) lib/thin/server.rb:162:in `start' rack (1.6.4) lib/rack/handler/thin.rb:19:in `run' rack (1.6.4) lib/rack/server.rb:286:in `start' railties (4.2.5) lib/rails/commands/server.rb:80:in `start' railties (4.2.5) lib/rails/commands/commands_tasks.rb:80:in `block in server' railties (4.2.5) lib/rails/commands/commands_tasks.rb:75:in `tap' railties (4.2.5) lib/rails/commands/commands_tasks.rb:75:in `server' railties (4.2.5) lib/rails/commands/commands_tasks.rb:39:in `run_command!' railties (4.2.5) lib/rails/commands.rb:17:in `<top (required)>' bin/rails:4:in `require' bin/rails:4:in `<main>' Here is a Gemfile: source 'http://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '>=4.2.4' # Use sqlite3 as the database for Active Record gem 'sqlite3' # Use SCSS for stylesheets gem 'sass-rails', '>=5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.1.0' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 0.4.0', group: :doc # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console #gem 'byebug' end group :development do # Access an IRB console on exception pages or by using <%= console %> in views gem 'web-console', '~> 2.0' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] gem 'therubyracer',:platform => :ruby gem 'pg' gem 'russian' gem 'thin' gem 'ransack' gem 'responders', '~> 2.0' gem 'acts_as_tree' gem 'd3-rails' gem 'c3-rails' gem 'bootstrap-datepicker-rails' gem 'momentjs-rails' gem 'select2-rails' gem 'chosen-rails' gem 'compass', '>=1.0.3' gem 'compass-rails', '>=2.0.4' |
Add custom class to simple_form_for association of type option - Rails Posted: 02 Dec 2016 05:45 AM PST I'm using a simple_form_for with a association = f.association :type, :collection =>version_name,:label => "Application type:", :selected =>'', :item_wrapper_class => 'lbl_type' This generates a html like below, <div class="control-group select optional"> <label class="select optional control-label" for="subscription_type_id">Application type:</label> <div class="controls"> <select class="select optional control-label" id="subscription_type_id" name="subscription[type_id]"> <option value="4">Type 1</option> <option value="5">Type 2</option> </select> </div> </div> I tried with item_wrapper_class but it is not working How to add specific custom classes to the control-label and to the input field Is there any way I can achieve this? |
What does ${PORT:-3000} mean in Heroku Procfile? Posted: 02 Dec 2016 05:00 AM PST |
Rails re-formatting my datetime Posted: 02 Dec 2016 05:14 AM PST I have a big query, which collects a collection of models, and I need to format the timestamps in the following manner: YYYY-MM-DDTHH:MI:SS.MSZ So, my query looks like: models.select("(to_char(created_at, 'YYYY-MM-DD') || 'T' || to_char(created_at, 'HH24:MI:SS.MSZ')) AS created_at").as_json But, when I get the result, I still get created_at field as a DateTime object. Nevertheless, if I rename the field in something else, like AS something_else , then I have my required format. How can I fix the problem, so that it will return created_at in my format, without going through the whole collection, and formatting each model ? UPDATE Database I am using is PostreSQL I traced this behaviour back to ActiveSupport::JSON::Encoder. I use the gem activesupport-json_encoder because I need the setting ActiveSupport.encode_big_decimal_as_string = false , while since Rails 4.1 they by default are encoded as strings. Now, this Encoder is encoding created_at and updated_at fields as ActiveSupport::TimeWithZone. Can I get rid of the latter somehow ? |
Rails - Confirmation of numeric attributes Posted: 02 Dec 2016 04:14 AM PST I've been trying Ruby on Rails for a few months now, re-engineering a desktop application. This application has a form for updating take-off and landing points, whose coordinates must be confirmed. Well, I tried validates_confirmation_of method however it works only with String attributes, and I have Integer and Decimal types. Hence I created an alternative method by borrowing an excerpt from the helper (confirmation.rb), which is working fine. But I wonder if there is another way to do it or whether this solution can be improved. Below follows a compact version of the source files. Thanks in advance! Migration: class CreateWaypoints < ActiveRecord::Migration[5.0] def change create_table :waypoints do |t| t.string :name t.integer :latitude_in_degrees t.integer :latitude_in_minutes t.decimal :latitude_in_seconds, precision: 5, scale: 2 t.timestamps end add_index :waypoints, [:name], unique: true end end View: <%= simple_form_for(@waypoint) do |f| %> <%= f.error_notification %> <div class="form-inline"> <%= f.input :name %> </div> <div class="form-inline"> <%= f.input :latitude_in_degrees %> <%= f.input :latitude_in_minutes %> <%= f.input :latitude_in_seconds %> </div> <div class="form-inline"> <%= f.input :latitude_in_degrees_confirmation, as: :numeric, label: false %> <%= f.input :latitude_in_minutes_confirmation, as: :numeric, label: false %> <%= f.input :latitude_in_seconds_confirmation, as: :numeric, label: false %> </div> <div class="form-actions"> <%= f.button :submit %> </div> <% end %> Model: class Waypoint < ApplicationRecord ... validates_each :latitude_in_degrees, :latitude_in_minutes, :latitude_in_seconds do |record, attribute, value| if record.send("#{attribute}_changed?") confirmed = record.send("#{attribute}_confirmation") confirmed == nil ? confirmed = 0 : confirmed = confirmed.to_d.round(2) # 2 matches migration. if confirmed != value human_attribute_name = record.class.human_attribute_name(attribute) record.errors.add(:"#{attribute}_confirmation", "Doesn't match #{human_attribute_name}") end end end end |
action is executing completely and two times the html is rendered but the content of the page is not loading without refreshing the page in rails Posted: 02 Dec 2016 06:12 AM PST This is my controller action def grant_spend_money set_organization_users_permission(:can_spend_money, true) end def revoke_spend_money set_organization_users_permission(:can_spend_money, false) end def set_organization_users_permission(permission_name, permission_value) @organization = current_user.organization organization_user = @organization.users.where(id: params[:user_id]).first organization_user.update_attribute(permission_name, permission_value) respond_to do |format| format.js { render :users_permission } end end This is user_permission.js.erb file $("#users_list").html("<%= escape_javascript(render partial: 'organization_user', collection: @organization.users.order(:id), as: :user) %>"); |
Rails - Are saving params in sessions a generally good idea for multistep forms? Posted: 02 Dec 2016 05:34 AM PST I'm generally new to Rails but have a decent understanding of MVC Architecture. With a Multistep form, I have been saving my params to my session and at the end of the multistep form pulling the values from the session and saving to my db. I want to save the data at the end of the multistep, not throughout the journey. An Example :- Form 1 Controller session[:user_details] = params Form 2 Controller @orders = Order.new @orders.first_name = session[:user_details]['first_name'] @orders.last_name = session[:user_details]['last_name'] @orders.save! Is this approach the best method given the scenario, or is there an alternate method in ruby which would be clearer? |
Cannot find data by ID from MySql using Ruby on Rails Posted: 02 Dec 2016 06:05 AM PST def show @item = Item.find(params[:id]) rescue ActiveRecord::RecordNotFound #customer with that id cannot be found redirect_to action: :index end ///////////////////////////////////////////////////////////////////////// def edit @item = Item.find(params[:id]) rescue ActiveRecord::RecordNotFound #customer with that id cannot be found redirect_to action: :index end Now the problem is it is not finding my data which exists in database. When i put new data then it works fine but only when I need to update or show that data on user requirement. Then it says record not found but at the same time the new input data can be put into data base as I told you before. |
how to override devise security extension PasswordExpiredController Posted: 02 Dec 2016 06:03 AM PST I want to override show logic in order to permit change password not only if it is expired, but some days earlier. I need to modify or replace this before_filter logic def skip_password_change return if !resource.nil? && resource.need_change_password? redirect_to :root end I want to make my controller like this: class PasswordsController < Devise::PasswordExpiredController # ... def skip_password_change return if !resource.nil? && (resource.need_change_password? || ... ) redirect_to :root end end How to achieve my goal? |
Batch check of checkboxes js Posted: 02 Dec 2016 04:15 AM PST I have a file: app/assets/javascripts/admin/batch_select.js $(document).ready(function() { $('#batch-select-all').on('change', function () { var selectAll = $('#batch-select-all :checkbox').prop('checked'); $('.table :checkbox').prop('checked', selectAll); }); }); to batch check checkboxes and in some views it 100% works, but not in this one: <% content_for :title do %>Reconciliaiton Assignment<% end %> <% content_for :additional_head do %> <%= javascript_include_tag 'admin/batch_select' %> <% end %> <main role="admin"> <div class="admin-header"> <% if @order_fulfillments.present? %> <%= render 'reconciliation_list' %> <% end %> </div> </main> _reconciliation_list.html.erb: <div class="row"> <div class="col-sm-12"> <div class="table-responsive"> <table id="reconAssignment" class="table table-condensed table-fixed"> <thead> <tr> <th id="batch-select-all"><input type="checkbox"></th> <th><span class="text-nowrap">Order Id</span></th> <th><span class="order-country">Country</span></th> </tr> </thead> <tbody> (<% @order_fulfillments.each do |fulfillment| %> <% reconciliations = filter_reconciliations(fulfillment.order_reconciliations) %> <% row_number = 0 %> <% if reconciliations.present? %> <% reconciliations.each do |reconciliation| %> <%= render 'reconciliation_list_row', fulfillment: fulfillment, order_reconciliation: reconciliation, row_number: row_number %> <% row_number += 1 %> <% end %> <% else %> <%= render 'reconciliation_list_row', fulfillment: fulfillment, order_reconciliation: nil, row_number: row_number %> <% end %> <% end %>) </tbody> </table> </div> </div> </div> _reconciliation_list_row.html.erb <tr id="row_<%= "#{fulfillment.id}_#{row_number}" %>"> <td id="batch-select"><input type="checkbox"></td> #doesnt batch check <td> <span class="text-nowrap"> <%= link_to admin_order_path(fulfillment.order_id), :target => "_blank" do %> <%= fulfillment.decorate.identifier %> <% end %> </span> </td> <td> <span class="text-nowrap"> <%= fulfillment.order.country.name %> </span> </td> </tr> |
Rendering 'form' is giving me an ArgumentError Posted: 02 Dec 2016 03:16 AM PST I am trying to create an activity feed, and trust me, it will take a while to create as I am new to ruby on rails. Sorry for a basic question. However, I am trying to render '_form.html.erb' as I want the user to be able to create a 'story' and for it to be listed on the same page, like any activity feed. Could someone explain to me what the problem is? My index.html.erb: <p id="notice"><%= notice %></p> <h1>This is a list of posts</h1> <table> <thead> <tr> <th>Name</th> <th>Description</th> <th>User</th> <th colspan="3"></th> </tr> </thead> <tbody> <% @stories.each do |story| %> <tr> <td><%= story.name %></td> <td><%= story.description %></td> <td><%= story.user.email %></td> <td><%= link_to 'Show', story %></td> <% if user_signed_in? %> <td><%= link_to 'Edit', edit_story_path(story) %></td> <td><%= link_to 'Destroy', story, method: :delete, data: { confirm: 'Are you sure?'} %></td> <% end %> </tr> <% end %> </tbody> </table> <%= link_to 'New Story', new_story_path %> <%= render 'form' %> _form.html.erb: <%= form_for @story do |f| %> <%= render 'shared/errors', object: @story %> <div class="form-group"> <%= f.label :name %> <%= f.text_field :name, class: 'form-control', required: true %> </div> <div class="form-group"> <%= f.label :description %> <%= f.text_area :description, class: 'form-control', required: true, cols: 3 %> </div> <%= f.submit 'Create Story', class: 'btn btn-primary' %> <% end %> Story Controller: class StoriesController < ApplicationController before_action only: [:destroy, :show, :edit, :update] def index @stories = Story.order('created_at DESC') end def new @story = current_user.stories.build end def create @story = current_user.stories.build(story_params) if @story.save flash[:success] = "Your beautiful story has been added!" redirect_to root_path else render 'new' end end def edit @story = Story.find(params[:id]) end def update @story = Story.find(params[:id]) if @story.update_attributes(params.require(:story).permit(:name, :description)) flash[:success] = "More knowledge, more wisdom" redirect_to root_path else render 'edit' end end def destroy @story = Story.find(params[:id]) if @story.destroy flash[:success] = "I think you should have more confidence in your storytelling" redirect_to root_path else flash[:error] = "Can't delete this story, sorry" end end def show @stories = Story.find(params[:id]) end private def story_params params.require(:story).permit(:name, :description) end end My error in terminal: ActionView::Template::Error (First argument in form cannot contain nil or be empty): 1: <%= form_for @story do |f| %> 2: <%= render 'shared/errors', object: @story %> 3: 4: <div class="form-group"> |
Create a model association where the model is not a active record model rails Posted: 02 Dec 2016 05:58 AM PST I have a model called Client. This extends not from ActiveRecord::Base but from my own wrapper class. These objects are not stored in my own database. I have some other models called Answer and Device for example. These are stored in my database with a client_id. Now, what I want to do is that is can call Answer.client and Client.answers for example. The normal way would be with ActiveRecord associations but that doesn't work is this case. I can define my own .answers and .client method but in my opinion that's not the way to go with Rails. Thanks in advance for replying! |
Rails. Test validation of picture size Posted: 02 Dec 2016 04:46 AM PST I have validation in my model, validate :picture_size , my model: class Post < ApplicationRecord belongs_to :user default_scope -> { order(created_at: :desc) } mount_uploader :picture, PictureUploader validates :content, presence: true, length: { maximum: 50_000 } validates :theme, presence: true, length: { minimum: 3, maximum: 100 }, uniqueness: { case_sensitive: false } validates :picture, presence: true validate :picture_size def to_param random_link end private def picture_size return unless picture.size > 5.megabytes errors.add(:picture, 'Файл должен быть меньше, чем 5МБ') end end My uploader: class PictureUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick process resize_to_limit: [600, 300] storage :file def default_url ActionController::Base.helpers.asset_path("default/no-photo-wide.png") end def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end def extension_white_list %w(jpg jpeg gif png) end end And it works well when I run rails server. But I wrote couple of tests, and it really somehow avoid validation and upload picture to my store dir. My test: let(:large_image) { Rack::Test::UploadedFile.new(File.open(File.join(Rails.root, '/spec/images/large-image.jpg'))) } it 'will give error if picture is more then 5mb' do post = Post.new(theme: 'foo', content: 'bar) post.picture = large_image post.save puts Post.first.picture expect(post.valid?).to be false end But result is true , not false . Can some tell where I made my mistake or suggest any other way to test picture size validation? |
Reporting in Rails with LaTeX using Models Posted: 02 Dec 2016 02:33 AM PST I would like to give my users the ability to create their own (PDF) reports in my Rails App. I think, the best way to accomplish that, is to use LaTeX, because it give a really nice output and many options to the user. Is there any Gem which i can use for that? Ruby-Toolbox give me some Gems - for example Rtex or rails-latex, but they doesnt seem to work with models (i would like to use a content field for the latex-erb stuff from my database). The only Gem i could find is ArTeX, which seems to be abandoned and not documented. Is there any better Gem for my purpose or is there any way i could use Rtex/rails-latex with my model-content? |
Nginx not found static files on remote server for Sinatra project Posted: 02 Dec 2016 06:24 AM PST I run first time sinatra project on remote server(ubuntu 14). Display errors from log nginx [error] 2308#2308: *1 "/home/deploy/name-project/public/index.html" is not found (2: No such file or directory) My app.rb file have folowing settings for static files: #app.rb require "sinatra" require "pry" require "sinatra/activerecord" require 'sinatra/flash' require 'sinatra/base' require "./models/user" require "./models/game_counter" require "./models/stash" require "json" require "pony" require 'logger' enable :static enable :sessions set :public_folder, File.dirname(__FILE__) + '/assets' configure :development do set :database, { adapter: "postgresql", database: "app_database", pool: 5, timeout: 5000 } end configure :production do set :database, { adapter: "postgresql", database: "app_prod", pool: 5, timeout: 5000, username: 'deploy', password: '123456' } end set :static_cache_control, [:public, {:no_store => 1}] db = ActiveRecord::Base.establish_connection(ENV['DATABASE_URL'] || 'postgres://localhost/app_database') LEVELS_TABLE = { '35': 'easy', '40': 'medium', '45': 'hard', '50': 'expert', '55': 'insane' } helpers do def current_user if session[:uid].present? User.find(session[:uid]) else return false end end end get '/' do @top_players = User.all.order('scores desc') @stashed_games = current_user ? current_user.stashes : [] if params[:stashed_game].present? @stashed_game = Stash.find(params[:stashed_game]) end @hidden = 'hidden' erb :index, :layout => :default end /etc/nginx/sites-enabled/default setting nginx. server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name domain.org; passenger_enabled on; passenger_ruby /usr/local/bin/ruby; root /home/deploy/name-project/public; # redirect server error pages to the static page /50x.html error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } How correct configure static files in sinatra project? On local server project running without errors |
How can I correctly test in minitest that, on a bad path for a method call, a notification service gets called? Posted: 02 Dec 2016 02:17 AM PST I am quite a newbie on minitest and I need help! My environment, to begin with, is: rails (4.2) minitest (5.9.1) as test framework mocha (1.2.1) as mock framework Let's say that I have this Job class: class GapCreationJob < ActiveJob::Base queue_as :default rescue_from ActiveRecord::RecordNotFound, StandardError do |error| handle_error(error) end def perform(gbu_id) # some code that might raise an exception... end private def handle_error(error) msg = "my message" Rollbar.warn(msg) Rails.logger.error "#{msg}\n Detail: #{error.message}" end end How should I write a test that checks that - in case of exception - the Rollbar.warn gets called? My problem, as newbie, is to write the expectation on the Rollbar class. I've tried this, but it does not work: require "test_helper" class GapCreationJobTest < ActiveJob::TestCase setup do # code that sets up @import @import = ... Rollbar = mock('rollbar') end test "a completely failing import job should notify us on rollbar" do GuestBusinessUnit.any_instance.expects(:set_activities_all).raises(ActiveRecord::RecordNotFound) GapCreationJob.any_instance.expects(:handle_error) # this works, but it is not sufficient Rollbar.expects(:warn) # this expectation is not satisfied, even if - on the testing class - the real Rollbar.expects method gets called GapCreationJob.perform_now(@import.id) end end Here is the output when I run this test: > rake test:jobs Running via Spring preloader in process 27705 Started with run options --seed 62075 GapCreationJobTest test_create_guest_activity_plans_after_guest_business_unit_creation PASS (1.42s) ~/Development/proj/test/jobs/gap_creation_job_test.rb:9: warning: already initialized constant GapCreationJobTest::Rollbar ~/Development/proj/test/jobs/gap_creation_job_test.rb:9: warning: previous definition of Rollbar was here test_a_completely_failing_import_job_should_notify_the_creator FAIL (0.02s) Minitest::Assertion: not all expectations were satisfied unsatisfied expectations: - expected exactly once, not yet invoked: #<Mock:rollbar>.warn(any_parameters) satisfied expectations: - expected exactly once, invoked once: #<AnyInstance:GuestBusinessUnit(id: integer, guest_id: integer, business_unit_id: integer, status: integer, datein: date, dateout: date, created_at: datetime, updated_at: datetime, idospite: string, conv_struttura: string, created_who: integer, updated_who: integer)>.set_activities_all(any_parameters) - expected exactly once, invoked once: #<AnyInstance:GapCreationJob>.handle_error(any_parameters) test/jobs/gap_creation_job_test.rb:22:in `block in <class:GapCreationJobTest>' Thank you very much! |
Connecting Microsoft SQL DB and MYSQL DB using Ruby Rails Posted: 02 Dec 2016 02:31 AM PST How To Connect Microsoft SQL DB and MYSQL DB using Ruby Rails i have tryed with follwing changes in database.yml MSSQL Connection development: adapter: sqlserver encoding: utf8 database: ****** pool: 5 host: *.*.*.* MYSQL Connection development: adapter: mysql2 encoding: utf8 database: ***** username: **** password: **** host: localhost getting following ERROR: database configuration does not specify adapter |
ajax request is completed but js.erb is not execution in rails Posted: 02 Dec 2016 02:08 AM PST ajax request is completed but js.erb is not execution in rails This is my js.erb $("#users_list").html("<%= escape_javascript(render partial: 'organization_user', collection: @organization.users.order(:id), as: :user) %>"); This my controller action def set_organization_users_permission(permission_name, permission_value) @organization = current_user.organization organization_user = @organization.users.where(id: params[:user_id]).first organization_user.update_attribute(permission_name, permission_value) respond_to do |format| format.js { render :users_permission } end end |
Name Clash with Top Level constant when autoloading with Rails Posted: 02 Dec 2016 03:05 AM PST I'm having a class Dog in app/models/dog.rb and another class Services::My::Deeply::Nested::Dog in app/services/my/deeply/nested/dog.rb . Now in Services::My (app/services/my.rb), I have a reference to one of the following (no need to distinguish, since the behaviour is exaclty the same in all situations): Deeply::Nested::Dog Services::My::Deeply::Nested::Dog ::Services::My::Deeply::Nested::Dog No matter which of the above I choose, I always get the following error message: services/my.rb: warning: toplevel constant Dog referenced by Services::My::Deeply::Nested::Dog Also, my deeply nested Dog never even gets seen by the interpreter (I found out by using puts and syntax errors, nothing happens). Possible workarounds (which I all don't like) are: - Rename one of the Dog classes
- Run with RAILS_ENV=production in order to disable autoloading and use eager loading instead
require_dependency that points to the deeply nested dog As a computer scientist, I find none of the above workarounds satisfactory. I would like to understand why my deeply nested Dog is not found without workaround and find out what the state-of-the-art Ruby / Rails solution would be for this problem. Thanks a lot in advance. |
Rails - update multiple active record relations Posted: 02 Dec 2016 01:21 AM PST I am doing an update all to a Model to update several ActiceRecord Relations. But I want to skip an attribute if its not provided (if its nil or empty I dont want to update that attribute) def update_numbers(numbers, comment) numbers.update_all (number_status: Number::STATUS_UPDATED, comment: comment if void_comment.present?) end This obviously does not work as it doesn't like the if condition. Is there a way to not try and update comment if its .blank? |
No comments:
Post a Comment