Postgresql JSON keys showing with underscores between letters? Posted: 22 Apr 2016 07:01 AM PDT I'm currently designing a web application that talks to a Rails API on top of a Postgres DB. I'm storing some of my data in JSON format using the jsonb datatype in Postgres. The keys in the Javascript objects I'm submitting to the Rails API are in all caps: { WEIGHT: 150, RACE: 'White / Caucasian', } The data submits just fine, but when I look in the database, the keys are stored with underscores between the letters, like this: { "W_e_i_g_h_t": 150, "R_a_c_e": "White / Causasian", } If I use the Rails console to create a model object from the DB, the keys are still stored in the same way, with underscores between the letters. But when the data comes back to my web app, the keys are back to all caps, no underscores. What is the reason for storing the keys in the database like this? |
Rails use base64 with user id in url? Posted: 22 Apr 2016 07:01 AM PDT I've been looking into the benefits of using base64 in urls and for files and I like the idea, and I can't seem to find anywhere to start. I have played around on the console encoding my picture urls too base64 which works okay(I can access it in the html decoding it in the view), My question would be how would I do this for urls? Instead of using 1.. 2.. 3 for my users, I would like to try and use base64 for the 'users/1' instead so it would be something like 'users/StormViper' for example |
502 bad gateway with Nginx, X-Accel-Redirect and Rails Posted: 22 Apr 2016 06:58 AM PDT I want to allow users to download files from a remote storage but I want to first auth the request through my rails app. I want to hand over the proxying of the remote file to nginx when rails has authenticated the request, to free up the ruby/rails thread. I have this nginx conf file called proxy_download.conf: # Proxy download location ~* ^/internal_redirect/(.*?)/(.*) { # Do not allow people to mess with this location directly # Only internal redirects are allowed internal; # Location-specific logging access_log logs/internal_redirect.access.log combined; error_log logs/internal_redirect.error.log warn; # Extract download url from the request set $download_uri $2; set $download_host $1; # Compose download url set $download_url http://$download_host/$download_uri; # Set download request headers proxy_set_header Host $download_host; proxy_set_header Authorization ''; # The next two lines could be used if your storage # backend does not support Content-Disposition # headers used to specify file name browsers use # when save content to the disk proxy_hide_header Content-Disposition; add_header Content-Disposition 'attachment; filename="$args"'; # Do not touch local disks when proxying # content to clients proxy_max_temp_file_size 0; # Download the file and send it to client proxy_pass $download_url; } I import this into the main nginx conf like so: include $ROOT/TO/APP/nginx.conf.d/proxy_download.conf; The app deploys fine and runs properly with this setup. These are the controller methods to start the download requeset: def x_accel_url(url, file_name = nil) uri = "/internal_redirect/#{url.gsub('http://', '').gsub('https://', '')}" uri << "?#{file_name}" if file_name return uri end def download if auth_is_ok # do some auth logic here headers['X-Accel-Redirect'] = x_accel_url('http://domain.com/file.ext') render :nothing => true end end When hitting this controller method through the browser, I get the famous nginx error: 502 Bad Gateway What's wrong with my setup? Thanks! |
implementing loader in rails app Posted: 22 Apr 2016 06:43 AM PDT I am trying to implement a loader in my rails app. The loader must be displayed as long as the page the user is requesting is not fully charged (Html + JS). I want this loader to be implemented on every page of my app but I cannot quite figure out the correct way to do that. So far I have created a _loader partial in my shared folder in the views folder: <div class="loader"></div> with some css : .loader { border: 16px solid #f3f3f3; /* Light grey */ border-top: 16px solid #3498db; /* Blue */ border-radius: 50%; width: 120px; height: 120px; animation: spin 2s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } What are the next steps to activate this loader as long as the page requested is not fully charged and thus hide the page as long as it's not fully charged. |
RSpec 3 RuntimeError: "let declaration accessed in a `before(:context)` hook" Posted: 22 Apr 2016 07:04 AM PDT Here is my error Failure/Error: @queue = FactoryGirl.create(model.to_s.underscore.to_sym) RuntimeError: let declaration `model` accessed in a `before(:context)` hook at: /var/www/html/SQ-UI/spec/support/user_queue/asterisk_serialize_spec.rb:7:in `block (2 levels) in <top (required)>' `let` and `subject` declarations are not intended to be called in a `before(:context)` hook, as they exist to define state that is reset between each example, while `before(:context)` exists to define state that is shared across examples in an example group.enter code here and here is the code where it's breaking let(:model) { described_class } # the class that includes the concern before(:all) do @queue = FactoryGirl.create(model.to_s.underscore.to_sym) end I've tried removing them and moving them around but no success. |
Ruby has_many model association not working Posted: 22 Apr 2016 06:58 AM PDT Here is two table properties and property_images I want to associate both table. properties id name status other-columns-here property_images id property_id image status Here is code - class Property < ActiveRecord::Base has_many :property_images, dependent: :destroy end class PropertyImage < ActiveRecord::Base belongs_to :property end users_controller.rb def index @properties = Property.order('id'); render html:@properties #13 properties coming end I have tried to has_many association but only coming properties data. Please help me |
ActiveRecord::RecordInvalid in OmniauthCallbacksController#twitter Validation failed: Email can't be blank Posted: 22 Apr 2016 06:23 AM PDT Whilst trying to implement Omniauth-twitter into my Rails app I've hit the error stated above. The error centres on a statement in my controller and I understand it relates to the fact twitter does not provide an email on callback. I'm using devise for authentication. I also intend to install Facebook omniauth but want to get Twitter working first. What code block can I implement to skip this validation for Twitter? Does it go in my controller or user model? Here's my code as it stands - OmniauthCallbacksController - class OmniauthCallbacksController < Devise::OmniauthCallbacksController def twitter @details = request.env["omniauth.auth"] @provider = @details["provider"] @provider_id = @details["uid"] @user = User.where(provider: @provider, provider_id: @provider_id).first if @user.present? #sign them in else # make a new user @user = User.new @user.provider = @provider @user.provider_id = @provider_id # because of has_secure_password - will this work? @user.password = "AAAAAA!!" @user.password_confirmation = "AAAAAA!!" # let's save the key and secret @user.key = @details["credentials"]["token"] @user.secret = @details["credentials"]["secret"] # lets fill in their details @user.name = @details["info"]["name"] @user.email = @details["info"]["email"] @user.save! end session[:uid] = @user.id flash[:success] = "You've logged in" redirect_to root_path end def password_required? super && provider.blank? end end routes.rb Rails.application.routes.draw do #get "/auth/:provider/callback" => "social_logins#create" devise_for :users, :controllers => { omniauth_callbacks: "omniauth_callbacks", registrations: 'registrations' } resources :users resources :events do resources :bookings end # get 'welcome/index' authenticated :user do root 'events#index', as: "authenticated_root" end root 'welcome#index' end User.rb class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, omniauth_providers: [:twitter] has_many :events has_many :bookings has_many :authentications end |
Rails can't send email after deployed to elastic beanstalk with credentials saved in figaro Posted: 22 Apr 2016 06:13 AM PDT I have rails app that deployed to the Elastic Beanstalk. I use figaro gemfile to save sensitive information such as my SendGrid url, username, and password. In development environment, it is working. Whenever I register with devise it will send the confirmation email. However in production environment it is not working as it suppose. Here is my production.rb: config.action_mailer.default_url_options = { host: 'bercareer.com' } config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = false config.action_mailer.default charset: "utf-8" # Use smtp for sending mail config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { domain: 'bercareer.com', address: ENV['SENGRID_URL'], port: 587, enable_starttsl_auto: true, user_name: ENV['SENDGRID_USERNAME'], password: ENV['SENDGRID_PASSWORD'], authentication: 'login' } Here is the error log in puma.log: Errno::ECONNREFUSED (Connection refused - connect(2) for nil port 587): /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/net/smtp.rb:541:in `initialize' /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/net/smtp.rb:541:in `open' /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/net/smtp.rb:541:in `tcp_socket' /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/net/smtp.rb:551:in `block in do_start' /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/timeout.rb:88:in `block in timeout' /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/timeout.rb:98:in `call' /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/timeout.rb:98:in `timeout' /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/net/smtp.rb:550:in `do_start' /opt/rubies/ruby-2.2.4/lib/ruby/2.2.0/net/smtp.rb:520:in `start' mail (2.6.4) lib/mail/network/delivery_methods/smtp.rb:113:in `deliver!' mail (2.6.4) lib/mail/message.rb:2149:in `do_delivery' mail (2.6.4) lib/mail/message.rb:237:in `block in deliver' actionmailer (4.2.5.1) lib/action_mailer/base.rb:543:in `block in deliver_mail' activesupport (4.2.5.1) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (4.2.5.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument' activesupport (4.2.5.1) lib/active_support/notifications.rb:164:in `instrument' actionmailer (4.2.5.1) lib/action_mailer/base.rb:541:in `deliver_mail' mail (2.6.4) lib/mail/message.rb:237:in `deliver' actionmailer (4.2.5.1) lib/action_mailer/message_delivery.rb:85:in `deliver_now' devise (3.5.6) lib/devise/models/authenticatable.rb:170:in `send_devise_notification' devise (3.5.6) lib/devise/models/confirmable.rb:116:in `send_confirmation_instructions' devise (3.5.6) lib/devise/models/confirmable.rb:172:in `send_on_create_confirmation_instructions' activesupport (4.2.5.1) lib/active_support/callbacks.rb:432:in `block in make_lambda' activesupport (4.2.5.1) lib/active_support/callbacks.rb:228:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:228:in `block in halting_and_conditional' activesupport (4.2.5.1) lib/active_support/callbacks.rb:506:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:506:in `block in call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:506:in `each' activesupport (4.2.5.1) lib/active_support/callbacks.rb:506:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:92:in `__run_callbacks__' activesupport (4.2.5.1) lib/active_support/callbacks.rb:778:in `_run_create_callbacks' activerecord (4.2.5.1) lib/active_record/callbacks.rb:306:in `_create_record' activerecord (4.2.5.1) lib/active_record/timestamp.rb:57:in `_create_record' activerecord (4.2.5.1) lib/active_record/persistence.rb:504:in `create_or_update' activerecord (4.2.5.1) lib/active_record/callbacks.rb:302:in `block in create_or_update' activesupport (4.2.5.1) lib/active_support/callbacks.rb:117:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:117:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:555:in `block (2 levels) in compile' activesupport (4.2.5.1) lib/active_support/callbacks.rb:505:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:505:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:92:in `__run_callbacks__' activesupport (4.2.5.1) lib/active_support/callbacks.rb:778:in `_run_save_callbacks' activerecord (4.2.5.1) lib/active_record/callbacks.rb:302:in `create_or_update' activerecord (4.2.5.1) lib/active_record/persistence.rb:120:in `save' activerecord (4.2.5.1) lib/active_record/validations.rb:37:in `save' activerecord (4.2.5.1) lib/active_record/attribute_methods/dirty.rb:21:in `save' activerecord (4.2.5.1) lib/active_record/transactions.rb:286:in `block (2 levels) in save' activerecord (4.2.5.1) lib/active_record/transactions.rb:351:in `block in with_transaction_returning_status' activerecord (4.2.5.1) lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `block in transaction' activerecord (4.2.5.1) lib/active_record/connection_adapters/abstract/transaction.rb:184:in `within_new_transaction' activerecord (4.2.5.1) lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `transaction' activerecord (4.2.5.1) lib/active_record/transactions.rb:220:in `transaction' activerecord (4.2.5.1) lib/active_record/transactions.rb:348:in `with_transaction_returning_status' activerecord (4.2.5.1) lib/active_record/transactions.rb:286:in `block in save' activerecord (4.2.5.1) lib/active_record/transactions.rb:301:in `rollback_active_record_state!' activerecord (4.2.5.1) lib/active_record/transactions.rb:285:in `save' devise (3.5.6) app/controllers/devise/registrations_controller.rb:17:in `create' actionpack (4.2.5.1) lib/action_controller/metal/implicit_render.rb:4:in `send_action' actionpack (4.2.5.1) lib/abstract_controller/base.rb:198:in `process_action' actionpack (4.2.5.1) lib/action_controller/metal/rendering.rb:10:in `process_action' actionpack (4.2.5.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action' activesupport (4.2.5.1) lib/active_support/callbacks.rb:117:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:117:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:555:in `block (2 levels) in compile' activesupport (4.2.5.1) lib/active_support/callbacks.rb:505:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:505:in `call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:92:in `__run_callbacks__' activesupport (4.2.5.1) lib/active_support/callbacks.rb:778:in `_run_process_action_callbacks' activesupport (4.2.5.1) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (4.2.5.1) lib/abstract_controller/callbacks.rb:19:in `process_action' actionpack (4.2.5.1) lib/action_controller/metal/rescue.rb:29:in `process_action' actionpack (4.2.5.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' activesupport (4.2.5.1) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (4.2.5.1) lib/active_support/notifications/instrumenter.rb:20:in `instrument' activesupport (4.2.5.1) lib/active_support/notifications.rb:164:in `instrument' actionpack (4.2.5.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action' actionpack (4.2.5.1) lib/action_controller/metal/params_wrapper.rb:250:in `process_action' activerecord (4.2.5.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action' actionpack (4.2.5.1) lib/abstract_controller/base.rb:137:in `process' actionview (4.2.5.1) lib/action_view/rendering.rb:30:in `process' actionpack (4.2.5.1) lib/action_controller/metal.rb:196:in `dispatch' actionpack (4.2.5.1) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch' actionpack (4.2.5.1) lib/action_controller/metal.rb:237:in `block in action' actionpack (4.2.5.1) lib/action_dispatch/routing/route_set.rb:74:in `call' actionpack (4.2.5.1) lib/action_dispatch/routing/route_set.rb:74:in `dispatch' actionpack (4.2.5.1) lib/action_dispatch/routing/route_set.rb:43:in `serve' actionpack (4.2.5.1) lib/action_dispatch/routing/mapper.rb:49:in `serve' actionpack (4.2.5.1) lib/action_dispatch/journey/router.rb:43:in `block in serve' actionpack (4.2.5.1) lib/action_dispatch/journey/router.rb:30:in `each' actionpack (4.2.5.1) lib/action_dispatch/journey/router.rb:30:in `serve' actionpack (4.2.5.1) lib/action_dispatch/routing/route_set.rb:815:in `call' warden (1.2.6) lib/warden/manager.rb:35:in `block in call' warden (1.2.6) lib/warden/manager.rb:34:in `catch' warden (1.2.6) lib/warden/manager.rb:34:in `call' rack (1.6.4) lib/rack/etag.rb:24:in `call' rack (1.6.4) lib/rack/conditionalget.rb:38:in `call' rack (1.6.4) lib/rack/head.rb:13:in `call' actionpack (4.2.5.1) lib/action_dispatch/middleware/params_parser.rb:27:in `call' actionpack (4.2.5.1) 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.1) lib/action_dispatch/middleware/cookies.rb:560:in `call' activerecord (4.2.5.1) lib/active_record/query_cache.rb:36:in `call' activerecord (4.2.5.1) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call' actionpack (4.2.5.1) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' activesupport (4.2.5.1) lib/active_support/callbacks.rb:88:in `__run_callbacks__' activesupport (4.2.5.1) lib/active_support/callbacks.rb:778:in `_run_call_callbacks' activesupport (4.2.5.1) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (4.2.5.1) lib/action_dispatch/middleware/callbacks.rb:27:in `call' actionpack (4.2.5.1) lib/action_dispatch/middleware/remote_ip.rb:78:in `call' actionpack (4.2.5.1) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' actionpack (4.2.5.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.2.5.1) lib/rails/rack/logger.rb:38:in `call_app' railties (4.2.5.1) lib/rails/rack/logger.rb:20:in `block in call' activesupport (4.2.5.1) lib/active_support/tagged_logging.rb:68:in `block in tagged' activesupport (4.2.5.1) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (4.2.5.1) lib/active_support/tagged_logging.rb:68:in `tagged' railties (4.2.5.1) lib/rails/rack/logger.rb:20:in `call' actionpack (4.2.5.1) 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.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' actionpack (4.2.5.1) lib/action_dispatch/middleware/static.rb:116:in `call' rack (1.6.4) lib/rack/sendfile.rb:113:in `call' railties (4.2.5.1) lib/rails/engine.rb:518:in `call' railties (4.2.5.1) lib/rails/application.rb:165:in `call' puma (3.4.0) lib/puma/configuration.rb:224:in `call' puma (3.4.0) lib/puma/server.rb:569:in `handle_request' puma (3.4.0) lib/puma/server.rb:406:in `process_client' puma (3.4.0) lib/puma/server.rb:271:in `block in run' puma (3.4.0) lib/puma/thread_pool.rb:114:in `call' puma (3.4.0) lib/puma/thread_pool.rb:114:in `block in spawn_thread' What did I do wrong? Thank you. |
I have a post http request in rails in which I have to send URL params along with body Posted: 22 Apr 2016 06:14 AM PDT The HTTP POST request is such that there are URL params and there is a body. Through postman, I am getting the response but when I am using Net::HTTP::Post, I am receiving no data. The URL params include user and token. The body contains collection_name which is a hash. How can I get the response using Net::HTTP::Post when I have URL params and body data. |
Redirect after only signup and login failure in devise rails Posted: 22 Apr 2016 06:42 AM PDT My login and signup forms are on home/index.html.erb. I want that when any of them fail error should show on index.html.erb . Now it redirect to devise views. How can I do that? Note : I want this only for signup and login. Password Forgot scenario will remain devise default |
Showing the person logged in on rails with devise gem Posted: 22 Apr 2016 06:12 AM PDT I'm trying to set up a "finish signing up page" in rails. So the plan is that the admin makes them an account with just an email and a password then sends them a link to log in and change their information. But I can't work out how to print out an update information form. I'm trying class Users < ApplicationController def update @current_nav_identifier = :signup @user.current_user = User.current_user end end and I was hoping that the form I have made will print out the update section so the user can update their information. However this doesn't happen, The @user.current_user = User.current_user throws an error so I changed to @user = User.new but this doesn't work because I don't want them to have access to add new users, they should only be able to change their information The idea is that when they sign in for the first time using the generated password they are redirected to this page so they can update their information. This web app is invite only Any ideas |
reduce the api call methods in ruby class Posted: 22 Apr 2016 05:32 AM PDT I have a rails application in which I am making multiple externa api calls. My code looks like this require 'api_class' class JsonFormatter class << self def format_json(json) formatted_json = JSON.parse(json) if formatted_json["response"]["status"] == "success" extract_values_from_json(formatted_json["response"]["node_message_context"]["message"]) end end def extract_values_from_json(formatted_json) collected_posts = [] community_stats = [] formatted_json.each do |key| collected_posts.push({ "body" => get_message_body(key), "board" => get_author_name(key), "subject" => get_subject(key) }) end collected_posts.uniq! {|post| post["body"] } end def get_message_body(message_obj) parsed_response = get_posts_data(message_obj) parsed_response["response"]["message"]["body"]["$"] end def get_posts_data(message_obj) @message_response = Api::HomePage.get_message_response(message_obj) JSON.parse(@message_response.body) end def get_subject(message_obj) parsed_response = get_posts_data(message_obj) parsed_response["response"]["message"]["subject"]["$"] end def get_author_name(message_obj) parsed_response = get_posts_data(message_obj) parsed_response["response"]["message"]["author"]["login"]["$"] end end Here to retrieve message body, board and subject details, I am calling get_posts_data(msgobj) which inturn calls the api and gets the response. I would like to reduce this api call. It would look better if I can store the response of api call to a variable and then I can refer the same message object variable for retrieving subject and author details. But I am not sure how to design it better. Any suggestions would be appreciated. |
Ruby on Rails: override pundit authorized work well in local but in production server is not Posted: 22 Apr 2016 05:26 AM PDT my application_controller.rb class ApplicationController < ActionController::Base include Pundit rescue_from Pundit::NotAuthorizedError, with: :not_authorized def not_authorized render 'shared/unauthorized', layout: 'application', :status => 401 end end my projects_controller.rb class ProjectsController < ApplicationController def show @project = Project.includes(:upload_documents).find(params[:id]) authorize @project end protected def not_authorized if current_user super else flash[:alert] = t('labels.project.messages.alert_sign_up') redirect_to new_user_registration_path end end end I debug my code very carefully and it worked as my expect in local. If authorize @project is false/nil, it will jump into not_authorized action in projects_controller.rb class ProjectPolicy def initialize(current_user, model) @current_user = current_user @project = model end def show? if @project.failed? || @project.pending? false else @current_user end end end But I debug in production server, it does not work like in local. After authorize @project in show action in projects_controller, it does not jump into not_authorized action. |
How to improve many level dependant destroy performance Posted: 22 Apr 2016 07:02 AM PDT In my project there are many models with has_many association and dependant: :destroy flag. Also, each model have other belong_to associations with the dependant: :destroy flag. This models are nested between each other so when a destroy is executed on the top one, Rails triggers cascading destroy on children models. Apart from that, models have callbacks that execute before_destroy . The following represents what I described above: class Model1Example < ActiveRecord::Base has_many :model2_examples, :dependent => :destroy belongs_to :other1_example, :dependent => :destroy belongs_to :other2_example, :dependent => :destroy end class Model2Example < ActiveRecord::Base belongs_to :model1_example has_many :model3_examples, :dependent => :destroy belongs_to :other3_example, :dependent => :destroy belongs_to :other4_example, :dependent => :destroy before_destroy :update_something_on_model1 before_destroy :check_some_inconsistence end class Model3Example < ActiveRecord::Base belongs_to :model2_example belongs_to :other5_example, :dependent => :destroy belongs_to :other6_example, :dependent => :destroy before_destroy :update_something_on_model2 before_destroy :check_some_inconsistence end Given that on average Model2Example holds about 100+ instances of Model3Example when the Model1Example destroy is triggered many SQL queries are triggered (10k+) because deletion is record by record and also all rules are executed for every instance...and this takes a lot more than what a user could wait for such a simple action. I could fix this performance issue by using dependant: :delete_all on the has_many associations instead, because I don't really care that all this rules are executed when I trigger Model1Example destroy . But the problem is that when I execute (from elsewhere in the app) a Model2Example destroy is in my interest that all rules are executed (specially Model3Example rules for each instance), and the previous mentioned approach brakes this. Is there a "Rails way" to achieve a performance improvement for this case? Or should I just use SQL for Model1Example deletion? Also, if I have to use this approach and I wanted to check some basic stuff before destroying Model1Example , where is the best place to do this validation? controller? |
Deploy rails app to digital ocean cap aborted! issue Posted: 22 Apr 2016 04:59 AM PDT I am trying to deploy my rails app on digital ocean. I am following Deploying a Rails App on Ubuntu 14.04 with Capistrano, Nginx, and Puma its my first time to deploy an app so it took more than a day to reach on 7th step But now when I put cap production deploy:initial in terminal it gives the following error DEBUG [63cf0a07] Running [ -d ~/.rvm ] on 162.243.10.38 DEBUG [63cf0a07] Command: [ -d ~/.rvm ] (Backtrace restricted to imported tasks) cap aborted! Net::SSH::Authentication::AgentError: agent could not sign data with requested identity Tasks: TOP => rvm:hook (See full trace by running task with --trace) |
How to set test enviroment with a large database? Posted: 22 Apr 2016 04:56 AM PDT I'm building an application with ruby on rails 4. It's a frontend to make searches in the database, and now I want to set the rails testing framework on it. But the standard test enviroment reset and repopulate the test database every time, and i have lots of data, so it's not practical. At the moment I made a local copy of the database, and overrided the db:reset task, so it won't be dropped every time. Is there a better way to do this? |
ruby: error running action after user update Posted: 22 Apr 2016 04:54 AM PDT I'm uploading a file that is saved on the user DB with carrierwave. After updating with the file, I want to call an action that copy that file to other location. My problem is that when I call that action it gives me this erro (Errno::EISDIR - Is a directory @ rb_sysopen) , because it doesn't recognize the file created, but if I refresh the file is in the DB (and if I call copy_file action on other location rather then in update it works well, but I want to copy the file only when the user uploads). This are my two actions, update, and after running the update calls copy_file: def copy_file require "fileutils" my_dir = Dir['./public/'+current_user.personal_file_url.to_s] my_dir.each do |filename| # name = File.basename('data', '.xml')[0,4] dest_folder = "./public/files/" FileUtils.cp(filename, dest_folder + "data.xml") # File.rename(filename, dest_folder + "/" + "data" + File.extname(filename)) end bat_file #redirect_to personal_performance_path end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update #upload personal file respond_to do |format| if @user.update(user_params) format.html { redirect_to :back, notice: 'File was sucessfully uploaded!' } format.json { render :show, status: :ok, location: @user } # copy_file #make a copy of the uploaded file in public/files/data.xml for running in the bat file else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end copy_file end |
filtering the datatable based on the date selected from fullcalender in rails Posted: 22 Apr 2016 04:48 AM PDT How do we write a query to filter the datatable based on the date returned by the fullcalender : i have written this in the fullcalender to get the date of the selected element select: function(start, end, jsEvent, view) { // start contains the date you have selected // end contains the end date. console.log(["Event Start date: " + moment(start).format('YYYY- MM-DD'), "Event End date: " + moment(end).format('YYYY-MM-DD')].join("\n")) How i use these two variables in my rails code for filtering the values based on the selected date . |
Error invoking PDFTK when modify PDF in Rails 4 Posted: 22 Apr 2016 04:47 AM PDT I am developing Rails 4 application where have to modify existing PDF file . User can write some comments and click then comments write in existing PDF as well. For this, i used gem 'pdf-toolkit' But i got below error: Error invoking PDFTK My Code: my_pdf = PDF::Toolkit.open("Credit_One.pdf") my_pdf.updated_at = Time.now # ModDate my_pdf["SomeAttribute"] = "Some value" my_pdf.save! Where is wrong any one have a idea. Thanks |
How to render custom form in active admin dashboard - Rails? Posted: 22 Apr 2016 05:39 AM PDT I want to render custom form in active admin dashboard page. Code looks like: apps/views/admin/dashboard/_form.html.erb <%= semantic_form_for :bill, builder: ActiveAdmin::FormBuilder,action:"new" do |f| %> <%= f.input :from_date%> <%= f.input :to_date%> <%= f.input :expiry_date%> <%=f.actions :submit %> <%end%> app/admin/dashboard.rb ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") } content title: proc{ I18n.t("active_admin.dashboard") } do columns do column do panel "Generate Bills" do render partial: 'form' end end column do panel "Pay Bills" do end end end end end I want new method of bill resource to be run on this form. because I want the active admin user to create bill objects from dashboard! help me out plzz. thnxx |
Rails asset pipeline custom folder and its dependents Posted: 22 Apr 2016 04:20 AM PDT I am trying to create a rails app and I have couple of css and js files to be added to rails app pipeline. These are; <link href="assets/plugins/pace/pace-theme-flash.css" rel="stylesheet" type="text/css" /> <link href="assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="assets/plugins/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css" /> <link href="assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css" media="screen" /> <link href="assets/plugins/bootstrap-select2/select2.css" rel="stylesheet" type="text/css" media="screen" /> <link href="assets/plugins/switchery/css/switchery.min.css" rel="stylesheet" type="text/css" media="screen" /> <link href="assets/plugins/codrops-stepsform/css/component.css" rel="stylesheet" type="text/css" media="screen" /> <link href="assets/plugins/bootsclertrap-datepicker/css/datepicker3.css" rel="stylesheet" type="text/css" media="screen"> <link href="assets/plugins/summernote/css/summernote.css" rel="stylesheet" type="text/css" media="screen"> <link href="assets/plugins/bootstrap-daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" media="screen"> <link href="assets/plugins/bootstrap-timepicker/bootstrap-timepicker.min.css" rel="stylesheet" type="text/css" media="screen"> <link href="assets/plugins/codrops-dialogFx/dialog.css" rel="stylesheet" type="text/css" media="screen" /> <link href="assets/plugins/codrops-dialogFx/dialog-sandra.css" rel="stylesheet" type="text/css" media="screen" /> <link href="pages/css/pages-icons.css" rel="stylesheet" type="text/css"> <link class="main-stylesheet" href="pages/css/themes/simple.css" rel="stylesheet" type="text/css" /> <link class="main-stylesheet" href="assets/css/style.css" rel="stylesheet" type="text/css" /> as in the theme I am trying to use. But if I only separate these css js and image, the problem is some of the css files are using img files inside their directory.For instance, select2.css uses background: url('select2.png') right top no-repeat; Or bootstrap min (I know I can add gem for this) uses url path to src:url(../fonts/glyphicons-halflings-regular.eot) . So should I go over css and js files and search for their dependents? I am so stuck in to designing this in a rails way. Thank you |
Ruby on rails. Sorting my model in a table using scopes and attributes Posted: 22 Apr 2016 04:15 AM PDT I've been at this for ages and can't get it right. I have a gig model and a couple of tables. In each table I need to show only gigs that meet certain requirements but there is one table that I cannot figure out. This table must contain gigs where: The table must NOT contain gigs where: - Expired and NOT filled. (date attribute in the past and filled attribute == false)
my scopes: scope :expiredr, -> { where('gigzonetime <= ?', Time.current.to_datetime)} scope :notfilled, -> {where(filled: false)} scope :filled, -> {where(filled: true)} scope :expired_and_filled, ->() {self.expiredr.merge(self.filled)} scope :expired_and_notfilled, ->() { self.expiredr.merge(self.notfilled) } I have tried loads of variations, eg. Controller: def dashboard if user_signed_in? && !current_user.try(:artist?) @activegigs = current_user.gigs.notcompleted.where.not(:expired_and_notfilled) @q = @activegigs.ransack(params[:q]) @dashgigs = @q.result(distinct: true).order(filled: :desc, reviewed: :desc, date: :asc).page(params[:page]).per(20) else redirect_to(root_url) flash[:danger] = "This page is for registered hosts only" end end which gives an RuntimeError at /gigs/dashboard unsupported: Symbol OR @activegigs = current_user.gigs.notcompleted && current_user.gigs.expired_and_filled && current_user.gigs.notexpired Which only shows expired_and_filled gigs. I am not sure how to negate the expired_and_notfilled scope or if that's even necessary. Any suggestions would be appreciated, thanks. |
Assets not found rails 4 + Capistrano 3 + Puma Posted: 22 Apr 2016 06:09 AM PDT I am deployed my rails project to the AWS. I have following in my Gemfile : group :development do gem 'capistrano' gem 'capistrano3-puma' gem 'capistrano-rails', '~> 1.1' gem 'capistrano-bundler', require: false gem 'capistrano-rvm' end In my production.rb config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? config.assets.compile = true config.assets.digest = true However, when I load my application in the web browser I see in the console that my application-xxxxxx.css and application-xxxxxx.js gives 404 not found error. Also, when I go to the server and look for the file in public/assets/ folder, the application-xxxxxx.js is present there. Can anyone help me with this? |
Where to set host for Rails.application.routes.url_helpers Posted: 22 Apr 2016 04:44 AM PDT In a controller I call a service like: MyService.call In the MyService.call method I want to use a url helper: Rails.application.routes.url_helpers.something_url However, I get the error: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true in config/environments/development.rb I have: config.action_mailer.default_url_options = { host: 'localhost:3000' } config.action_controller.default_url_options = { host: 'localhost:3000' } What should I set not to get the error? |
How to implement multiple social share buttons or add its attributes according to the selected social network? Posted: 22 Apr 2016 04:07 AM PDT I am using this lib. to share the content on fb, twiiter and pintrest. I have defined the social share button as: = social_share_button_tag (@campaign_twitter_text, 'data-twitter-title' => @campaign_twitter_text, 'data-facebook-title' => @campaign_fb_text, :url => @campaign_share_link, :image => @campaign_fb_image) Now in my rails application, user can edit twitter, fb and pinterest share message(this could be different for all 3). My question is how do i configure this social share button tag to either have different message, photo. It is configured as: SocialShareButton.configure do |config| config.allow_sites = %w(twitter facebook pinterest) end i want to configure such that it can share different messsage and image. I looked all around the library but could not found any handle to do so. Any help please. |
Passenger 5.0.21 error: Cannot connect to the Passenger core Posted: 22 Apr 2016 03:18 AM PDT I have problem with deploying RoR-app with apache2+passenger. OS is debian-like Astra Linux. Kerberos auth with GSSAPI is enabled. passenger-status shows: Version : 5.0.21 Date : 2016-04-22 12:29:13 +0300 Instance: Dt5dmAVr (Apache/2.2.22 (Debian) mod_auth_kerb/5.4 Phusion_Passenger/5.0.21) Phusion Passenger is currently not serving any applications. With attempt to access app page from browser I get error message in /var/log/apache2/error.log : [ 2016-04-22 12:23:58.4672 21392/7f741705c780 age/Cor/CoreMain.cpp:234 ]: Passenger core running in multi-application mode. [ 2016-04-22 12:23:58.4685 21392/7f741705c780 age/Cor/CoreMain.cpp:707 ]: Passenger core online, PID 21392 [ 2016-04-22 12:23:58.4897 21407/7f4819471780 age/Ust/UstRouterMain.cpp:504 ]: Starting Passenger UstRouter... [ 2016-04-22 12:23:58.4912 21407/7f4819471780 age/Ust/UstRouterMain.cpp:317 ]: Passenger UstRouter online, PID 21407 [Fri Apr 22 12:23:58 2016] [notice] Apache/2.2.22 (Debian) mod_auth_kerb/5.4 Phusion_Passenger/5.0.21 configured -- resuming normal operations [ 2016-04-22 12:24:18.0666 21428/7f3a64646780 apa/Hooks.cpp:703 ]: Unexpected error in mod_passenger: Cannot connect to the Passenger core at unix:/tmp/passenger.N6n3OMb/agents.s/core Backtrace: in 'Passenger::FileDescriptor Hooks::connectToCore()' (Hooks.cpp:305) in 'int Hooks::handleRequest(request_rec*)' (Hooks.cpp:573) With passenger-5.0.27 everything looks same. Passenger was installed as gem. /etc/apache2/mods-enabled/passenger.load: LoadModule passenger_module /usr/local/lib/ruby/gems/2.2.0/gems/passenger-5.0.21/buildout/apache2/mod_passenger.so /etc/apache2/mods-enabled/passenger.conf: <IfModule mod_passenger.c> PassengerRoot /usr/local/lib/ruby/gems/2.2.0/gems/passenger-5.0.21 PassengerDefaultRuby /usr/local/bin/ruby </IfModule> /etc/apache2/sites-enabled/myapp: <VirtualHost *:80> ServerName myapp.ru ServerAlias www.myapp.ru ServerAdmin webmaster@localhost DocumentRoot /var/www/myapp/public RailsEnv production <Directory /var/www/myapp/public/> AuthType Kerberos KrbAuthRealms EXAMPLE.RU KrbServiceName HTTP/astra-server.example.ru Krb5Keytab /etc/apache2/keytab KrbMethodNegotiate on KrbMethodK5Passwd off require valid-user Options Indexes FollowSymLinks MultiViews AllowOverride None </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined LogLevel warn </VirtualHost> Any help? |
how to set array params in get request in rails Posted: 22 Apr 2016 03:25 AM PDT I use http get in rails. There are array params in the request. How can I encode the params into the request? My code is like the next: uri = URI(url) uri.query = URI.encode_www_form(params) if params resp = Net::HTTP.get_response(uri) data = resp.body When the params have an array, such as ids, the url will like "http://url?ids=1&ids=2" , but I want to the url like "http://url?ids[]=1&ids[]=2" . |
How do you create multiple channels with Actioncable; how does one pass an in-document variable to the javascript and ruby channels and jobs? Posted: 22 Apr 2016 03:17 AM PDT For example, in https://www.youtube.com/watch?v=n0WUjGkDFS0 at 10:36 he mentions the ability to create multiple channels, but how would one actually accomplish this? According to Rails 5 ActionCable establish stream from URL parameters a variable can be defined and passed as a parameter like: def subscribed stream_from "room_channel_#{params[:roomId]}" end But in the javascript file prior to passing the data here, how does one pass in the data from the page? The following example renders an error as presumably the cable is defined before the document is loaded. App.room = App.cable.subscriptions.create { channel: "RoomChannel", roomId: document.getElementById("message_text").getAttribute("data-room")} Then, if one does successful get the data from the document into the variable here and passes it to the stream_from method, then lastly, how does the right channel get passed into the perform method to be used in the broadcast job? def perform(message) ActionCable.server.broadcast 'room_channel_???', message: render_message(message) #, roomId: roomId end Thanks! |
How can I do full text search using elasticsearch in Rails 4 in Heroku? Posted: 22 Apr 2016 03:10 AM PDT I am still struggling with full-text search. Problem I have now: EX) If I have textbook titles "java140", "java-1", "java333", and "java1", I tpye "java" as a query which is params[:search] , but I can see only "java-1" . I have a model Textbook : require 'elasticsearch/model' class Textbook < ActiveRecord::Base extend FriendlyId friendly_id :title, use: :slugged include Elasticsearch::Model include Elasticsearch::Model::Callbacks belongs_to :user #below paperclip options. "500x500>" tells resize&shrunk if need has_attached_file :thumbnail, styles: { original: "1000x1000>", :large => "1000x1000", medium: "300x300>", thumb: "100x100>" }, :convert_options => { original: "-quality 85 -strip", :thumb => '-quality 80' } validates_attachment_content_type :thumbnail, content_type: /\Aimage\/.*\Z/ validates_attachment_size :thumbnail, :less_than => 4.megabytes, :message => "must be LESS than 4MB" #include ActiveModel::Validations validates :title, :presence => true validates :subject, :presence => true validates :price, :presence => true validates :offer, :presence => false validates :created_at, :presence => false validates :user_email, :presence => true validates :description, :presence => false validates_length_of :title, :maximum => 30 validates_length_of :subject, :maximum => 20 validates_length_of :price, :maximum => 5 mappings do indexes :title, analyzer: 'english' indexes :subject, analyzer: 'english' end #below http://www.sitepoint.com/full-text-search-rails-elasticsearch/ def self.search(query) __elasticsearch__.search( { query: { multi_match: { query: query, fields: ['title^10', 'subject'] } } } ) end end Textbook.import code of search section form in my views/textbooks/index.html.erb : At below the :name => nil what's this for? should I change to :title => nil ?? <div> <%= form_tag search_textbook_path, :method => :get do %> <p> <a style="color:#000000" title="Suggest!" data-toggle="popover" data-trigger="hover" data-content="Title or Subject"> <%= text_field_tag :search, params[:search], placeholder: "Search textbooks" %> </a> <%= submit_tag "Search", :name => nil, class: "btn btn-success btn-sm" %> <% end %> </div> This is my search_controller.rb : class SearchController < ApplicationController #https://www.youtube.com/watch?v=Pse-2ZkVaTs&list=PLjQo0sojbbxWcy_byqkbe7j3boVTQurf9 def search_textbook @textbooks = Textbook.search((params[:search].present? ? params[:search] : '*')).records.order(created_at: :desc) # --------I am trying belows-------- # @textbooks = Textbook.search('{"search": {"match": {"_all": params[:search]}}}').records # @textbooks = Textbook.search index: 'textbooks', body: { query: { match: { title: params[:query] } } } end end I get error, when I use @textbooks = Textbook.search index: 'textbooks', body: { query: { match: { title: params[:query] } } } @textbooks = Textbook.search('{"search": {"match": {"_all": params[:search]}}}').records gives me nothing I mean no results. Error I get is this: Error picture |
Is there any way to define invalid enum value in a model? Posted: 22 Apr 2016 03:05 AM PDT I have a model as: class CashPayment < ActiveRecord::Base ..... **enum status: [:processing, :paid, :invalid,:refund]** end Here,I have declared invalid status for cash_payment.But its giving me as error like: *** ArgumentError Exception: You tried to define an enum named "status" on the model "CashPayment", but this will generate a instance method "invalid?", which is already defined by Active Record |
No comments:
Post a Comment