HttpParty Proxy ip address usage Posted: 16 Jul 2016 07:46 AM PDT So i have a call to an api, Looks like this (url removed for safety yada yada) apicall = HTTParty.get(URI.encode('URL HERE'), headers: {"Authorization" => "Bearer apikey"}).parsed_response Now what i'm wanting is to use my proxy ip address to access the web page. Would you be willing to point me in the right direction to do this? I've aware how to do this in open-uri but not sure if its possibe to do a get request with a this gem. Thanks Sam |
Hard time understanding Httparty gem implementation into rails Posted: 16 Jul 2016 07:06 AM PDT i'm new to ruby and to rails and i have quite a hard time understanding how to properly use httparty gem since i'm in need of using it. Let's say i have a model of Product and i'm getting 20 products from api.products/product/list in JSON format. Using api.products/product/1 i get a product with an id of 1. In documentation of Httparty there is no explanation of @options variable and how it is used. I couldn't find a description of .get method neither in rails documentation. I'm having a Product model and 2 class methods that are acquireing data using api calls (all and find(id)) and i'm using the same Product model then to initialize array of Product objects (using class method all) or one Product (using class method find(id)). In initialize i only need couple of attributes for Product attributes (id, name, price) and i have no need for @options attribute. How can i accomplish this using HTTParty using this structure in a class Product Thanks |
How to filter out results by their ranking score with PG search? Posted: 16 Jul 2016 06:43 AM PDT I am using pg_search for searching Articles within my app. Problem is that I get too many results back. I would like to filter out the results that are less than say, 0.09 in their relevancy score. I am assuming I might need to go down the rabbit hole and do something like: if query.present? rank = <<-RANK ts_rank(to_tsvector(name), plainto_tsquery(#{sanitize(query)})) + ts_rank(to_tsvector(content), plainto_tsquery(#{sanitize(query)})) RANK where("to_tsvector('english', name) @@ :q or to_tsvector('english', content) @@ :q", q: query).order("#{rank} desc") ... I am wondering whether there's a simpler and more readable way to achieve that. My model: class Article < ActiveRecord::Base validates :content, presence: true include PgSearch pg_search_scope :search, against: { title: 'A', h1: 'B', content: 'C', meta_description: 'C' }, using: { tsearch: { dictionary: 'english', any_word: true, highlight: { start_sel: '<strong>', stop_sel: '</strong>' } } } def self.text_search(query) if query.present? search(query) #.with_pg_search_highlight else [] end end end My controller: def search @articles = Article.search(params[:search]).with_pg_search_highlight end |
nprogress-rails with turbolinks not working in rails 4.2.6 Posted: 16 Jul 2016 06:12 AM PDT i'm trying to use gem nprogress-rails : https://github.com/caarlos0/nprogress-rails with Turbolinks, but even requiring it in application.js and application.css.scss it doesn't load or work. There's no error in browser console and the javascript files nprogress.js and nprogress-turbolinks are loaded in every page refresh. Here is my application.js : //= require jquery //= require jquery_ujs //= require nprogress //= require nprogress-turbolinks //= require turbolinks //= require_tree . And here is my application.css.scss : *= require nprogress *= require_tree . *= require_self Lastly, my Gemfile includes the gem nprogress-rails : source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.6' # Use postgresql as the database for Active Record gem 'pg', '~> 0.15' # 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 gem 'nprogress-rails' # 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' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end Anyone can help me? Thank you. |
How to render a google drive file in to rails app Posted: 16 Jul 2016 06:09 AM PDT I have some html files stored in Google drive, I wanted those files to render in to my new rails app, is there any possibility to render a view of the Google drive file in to rails app ? Please help me. Thanks. |
Submitting a form to Rails with ReactJS Posted: 16 Jul 2016 06:08 AM PDT I'm trying to submit a simple form to my Rails app. I lost myself in confusion and nothing's working. This is what I have tried to do: var newUserForm = React.createClass({ propTypes: { users: React.PropTypes.array }, getInitialState: function() { return {name: '', age: '', country: '' }; }, handleNameChange: function(e) { this.setState({ name: e.target.value }); }, handleAgeChange: function(e) { this.setState({ age: e.target.value }); }, handleCountryChange: function(e) { this.setState({ country: e.target.value }); }, handleSubmit: function(e) { e.preventDefault(); var name = this.state.name.trim(); var age = this.state.age.trim(); var country = this.state.country.trim(); if (!name || !age || !country) { return; } this.setState({ name: '', age: '', country: '' }); var users = this.state.data; user.id = Date.now(); var newUsers = users.concat([user]); this.setState({data: newUsers}); $.ajax({ url: this.props.url, dataType: 'json', type: 'POST', data: user, success: function(data) { this.setState({data: user}); }.bind(this), error: function(xhr, status, err) { this.setState({data: users}); console.error(this.props.url, status, err.toString()); }.bind(this) }); }, render: function() { return ( <form onSubmit={this.handleSubmit}> <input type="text" placeholder="User's name" value={this.state.name} onChange={this.handleNameChange} /> <input type="text" placeholder="His age" value={this.state.age} onChange={this.handleAgeChange} /> <input type="text" placeholder="Country of origin" value={this.state.country} onChange={this.handleCountryChange} /> <input type="submit" value="Post"/> </form> ) } }); And my console: I need some help. |
Regarding will_paginate using an explicit "per page" limit - Rails 4.2.0 Posted: 16 Jul 2016 05:54 AM PDT For instance, I have got a Post model and I will achieve per page limit of 10 in the way as below; Post.paginate(:page => params[:page], :per_page => 10) But my question is, How would I limit pages randomly. For example, for the first page I want to show 10 records and on the second page I want to show 15 records and so on. How would I implement this in my rails application. Any suggestions are most welcome. Thank you in advance. |
Rails, best_in_place gem for mobile phones Posted: 16 Jul 2016 05:52 AM PDT I rewrote my rails app today so that it works with the best_in_place gem. Now I launched the app on my phone and for an unpleasant surprise, I found that the best_in_place fields do not respond to touch. Any ideas how to make that gem recognise touch events? Thank you! |
EOFError: Bad Content Body in API Posted: 16 Jul 2016 05:39 AM PDT There's a few other stack posts around similar errors, though the trace of mine highlights different method failures and typically these errors occur in multipart forms, which mine is not. I've been looking at this problem on and off for a few weeks now and decided it was time to ask others for help. The scenario: I have an API mounted engine which I built. It's lightweight, has a controller and a method to receive post requests with data logs. These logs are often 60,000~ bytes in size and are accessed through request.body.read . To make sure it wasn't an error provoked by my code. I removed everything, it's literally an empty method that just returns 200 now. Like this: def tcpdata return 200 end Yet, I still get the error. Which makes it really frustrating because it seems out of my hands. The error I get is ERROR EOFError: bad content body and it's failing in the rack multipart method get_current_head_and_filename_and_content_type_and_name_and_body Here's the full trace: 2016-07-16T12:31:06.624089+00:00 heroku[router]: at=info method=POST path="/api/endpoint/devices" host=getbeambox.com request_id=992b3308-97db-4dbe-9ab0-343ee0a4f49f fwd="79.77.176.13,141.101.99.214" dyno=web.1 connect=1ms service=309ms status=500 bytes=507 2016-07-16T12:31:06.627426+00:00 app[web.1]: [2016-07-16 12:31:06] ERROR EOFError: bad content body 2016-07-16T12:31:06.627448+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/multipart/parser.rb:148:in `get_current_head_and_filename_and_content_type_and_name_and_body' 2016-07-16T12:31:06.627450+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/multipart/parser.rb:59:in `block in parse' 2016-07-16T12:31:06.627451+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/multipart/parser.rb:56:in `loop' 2016-07-16T12:31:06.627452+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/multipart/parser.rb:56:in `parse' 2016-07-16T12:31:06.627452+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/multipart.rb:25:in `parse_multipart' 2016-07-16T12:31:06.627453+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/request.rb:375:in `parse_multipart' 2016-07-16T12:31:06.627454+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/request.rb:207:in `POST' 2016-07-16T12:31:06.627454+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/methodoverride.rb:39:in `method_override_param' 2016-07-16T12:31:06.627455+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/methodoverride.rb:27:in `method_override' 2016-07-16T12:31:06.627456+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/methodoverride.rb:15:in `call' 2016-07-16T12:31:06.627457+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.15.0.314/lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call' 2016-07-16T12:31:06.627458+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/runtime.rb:18:in `call' 2016-07-16T12:31:06.627459+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.15.0.314/lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call' 2016-07-16T12:31:06.627459+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.4/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' 2016-07-16T12:31:06.627460+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.15.0.314/lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call' 2016-07-16T12:31:06.627461+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/static.rb:116:in `call' 2016-07-16T12:31:06.627462+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.15.0.314/lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call' 2016-07-16T12:31:06.627463+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/sendfile.rb:113:in `call' 2016-07-16T12:31:06.627463+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.15.0.314/lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call' 2016-07-16T12:31:06.627464+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/engine.rb:518:in `call' 2016-07-16T12:31:06.627465+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.4/lib/rails/application.rb:165:in `call' 2016-07-16T12:31:06.627466+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/newrelic_rpm-3.15.0.314/lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call' 2016-07-16T12:31:06.627466+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/lock.rb:17:in `call' 2016-07-16T12:31:06.627467+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/content_length.rb:15:in `call' 2016-07-16T12:31:06.627468+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.4/lib/rack/handler/webrick.rb:88:in `service' 2016-07-16T12:31:06.627469+00:00 app[web.1]: /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service' 2016-07-16T12:31:06.627469+00:00 app[web.1]: /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run' 2016-07-16T12:31:06.627470+00:00 app[web.1]: /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread' |
sending mail via IMAP through action-mailer in rails Posted: 16 Jul 2016 05:28 AM PDT i am already implemented send mail through smtp protocol now i trying to implement via IMAP..protocol....what should i have to change in config/devlopment .rb config.action_mailer.default_url_options = { host: 'localhost', port: 9292} config.action_mailer.delivery_method = :smtp ActionMailer::Base.smtp_settings = { address: 'imap.gmail.com'or'imap.hotmail.com'or'imap.yahoo.com', # default: localhost port: '25', # default: 25 user_name: 'debasish.industrify2016@gmail.com', password: 'debxxxxxxxx', authentication: :plain # :plain, :login or :cram_md5 } |
Why creation of custom Exceptions needed Posted: 16 Jul 2016 05:32 AM PDT So, the question is in the title. The only one thought that comes in mind why we need to introduce custom Exception class is to pass additional info with exception raising. Any additional reasons? |
Rails rspec error: wrong number of arguments (0 for 1) Posted: 16 Jul 2016 04:54 AM PDT I am new to rails and rspec, and currently taking an online a tutorial. In the tutorial I am running the following code: def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end board = [" "," "," "," "," "," "," "," "," "] display_board(board) When I run the test I get the following output: /lib/display_board.rb defines a method display_board #display_board method represents a cell as a string with 3 spaces (FAILED - 1) Failures: 1) /lib/display_board.rb #display_board method represents a cell as a string with 3 spaces Failure/Error: def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end ArgumentError: wrong number of arguments (0 for 1) # ./lib/display_board.rb:2:in `display_board' # ./spec/display_board_spec.rb:10:in `block (4 levels) in <top (required)>' # ./spec/spec_helper.rb:5:in `capture_puts' # ./spec/display_board_spec.rb:10:in `block (3 levels) in <top (required)>' Finished in 0.00296 seconds (files took 0.14604 seconds to load) 2 examples, 1 failure Failed examples: rspec ./spec/display_board_spec.rb:9 # /lib/display_board.rb #display_board method represents a cell as a string with 3 spaces The test case is as follows: it 'represents a cell as a string with 3 spaces' do output = capture_puts{ display_board } expect(output).to include(" ") end Where line 10 is the spec file is "output = capture_puts{ display_board }" And "capture_puts" is defined in the spec_helpr.rb as follows: def capture_puts begin old_stdout = $stdout $stdout = StringIO.new('','w') yield $stdout.string ensure $stdout = old_stdout end end I searched for the error "wrong number of arguments (0 for 1)", but I didn't get any useful result. Please advice since I am really a beginner with Ruby and Rails. |
Direct image upload with Rails and Amazon S3 Posted: 16 Jul 2016 04:04 AM PDT I've been trying to implement direct image upload to S3 with Paperclip and s3_direct_upload gems. I've followed this 'Little Blimp Dev Blog' post and got the example project working but it seems to be not complete: - It doesn't upload image versions like thumb, icon etc.
- It doesn't save uploaded image's S3 URL to database
How can I achieve these? |
How to search model by date and day [duplicate] Posted: 16 Jul 2016 04:12 AM PDT This question already has an answer here: By using a railscast video i create a simple search that works on same model. And i have fields for date, day and time. my model class Sale < ApplicationRecord belongs_to :washer, optional: true belongs_to :location, optional: true has_many :sale_services has_many :services, :through => :sale_services def day created_at.strftime('%A') end def time created_at.strftime("%H:%M") end def date created_at.strftime('%F') end def self.search(search) if search key = "'%#{search}%'" columns = %w{ city station venue area country plate_number } joins(:services).joins(:washer).joins(:location).where(columns.map {|c| "#{c} ILIKE #{key}" }.join(' OR ')) else where(nil) end end end What do i need to change to be sure i can search for day, and date on a timestamp field? |
Rails Simple Form - No route matches Posted: 16 Jul 2016 04:16 AM PDT Each user can create a number of blogs and, when they log in, they are presented with a list of their blogs and a button next to each as below: = simple_form_for activate_blog_path(blog.id), method: :put do |f| = hidden_field_tag :active, value: true = f.button :submit Even though the path exists in routes, I'm still getting this error message: No route matches [PUT] "/" routes.rb: resources :users resources :blogs do member do get :activate put :activate end end root 'pages#index' rails routes: Prefix Verb URI Pattern Controller#Action users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#new edit_user GET /users/:id/edit(.:format) users#edit user GET /users/:id(.:format) users#show PATCH /users/:id(.:format) users#update PUT /users/:id(.:format) users#update DELETE /users/:id(.:format) users#destroy activate_blog GET /blogs/:id/activate(.:format) blogs#activate PUT /blogs/:id/activate(.:format) blogs#activate blogs GET /blogs(.:format) blogs#index POST /blogs(.:format) blogs#create new_blog GET /blogs/new(.:format) blogs#new edit_blog GET /blogs/:id/edit(.:format) blogs#edit blog GET /blogs/:id(.:format) blogs#show PATCH /blogs/:id(.:format) blogs#update PUT /blogs/:id(.:format) blogs#update DELETE /blogs/:id(.:format) blogs#destroy root GET / pages#index blogs_controller.rb: def activate @blog.active = true @blog.save redirect_to root_path end What am I doing wrong here? |
Rails Console results in PG::ConnectionBad: fe_sendauth: no password supplied Posted: 16 Jul 2016 07:00 AM PDT In Prodcution when i try to access the rails c and run any command on the Database i am getting the following error 2.3.1 :001 > Campaign.all PG::ConnectionBad: fe_sendauth: no password supplied from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/postgresql_adapter.rb:651:in `initialize' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/postgresql_adapter.rb:651:in `new' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/postgresql_adapter.rb:651:in `connect' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/postgresql_adapter.rb:242:in `initialize' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/postgresql_adapter.rb:44:in `new' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/postgresql_adapter.rb:44:in `postgresql_connection' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:438:in `new_connection' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:448:in `checkout_new_connection' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:422:in `acquire_connection' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:349:in `block in checkout' from /usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:348:in `checkout' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:263:in `block in connection' from /usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:262:in `connection' from /usr/local/rvm/gems/ruby-2.3.1/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/abstract/connection_pool.rb:571:in `retrieve_connection' ... 22 levels... from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-4.2.5.2/lib/rails/commands/console.rb:9:in `start' from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:68:in `console' from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:39:in `run_command!' from /usr/local/rvm/gems/ruby-2.3.1/gems/railties-4.2.5.2/lib/rails/commands.rb:17:in `<top (required)>' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `require' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `block in require' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:240:in `load_dependency' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `require' from /home/rails/skreem-ror/bin/rails:9:in `<top (required)>' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:268:in `load' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:268:in `block in load' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:240:in `load_dependency' from /usr/local/rvm/gems/ruby-2.3.1/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:268:in `load' from /usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from /usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' I have set the Passwords in the environment variables. Any solution on how to change it? rails@skreem-production:~/skreem-ror$ rails c production Running via Spring preloader in process 6158 Loading production environment (Rails 4.2.5.2) 2.3.1 :001 > Rails.env => "production" 2.3.1 :002 > Rails.application.config.database_configuration[Rails.env] => {"adapter"=>"postgresql", "encoding"=>"unicode", "pool"=>5, "host"=>"localhost", "username"=>"rails", "password"=>nil, "database"=>"skreem_production"} 2.3.1 :003 > |
Bundle install is not working Posted: 16 Jul 2016 06:10 AM PDT |
How to have search functionality on association models as well Posted: 16 Jul 2016 03:37 AM PDT By using a railscast video i create a simple search that works on same model. But now i have a model that shows associated model data as well and i would like to search on them as well. Right now i managed to make it semi work, but i assume i have conflict if i add the field "name" into the joins as i have two models that have a column named "name" def self.search(search) if search key = "'%#{search}%'" columns = %w{ city station venue area country plate_number } joins(:services).joins(:washer).joins(:location).where(columns.map {|c| "#{c} ILIKE #{key}" }.join(' OR ')) else where(nil) end end What do i need to change to be sure i can search across all columns? |
How to add records to a table based on another Posted: 16 Jul 2016 03:19 AM PDT I am an app that is a multi-tenant e-commerce site whereby we have a default set of products that the tenant can use to either sell or not. At present my models are Merchant which has a Merchant Type Merchant Type which belongs to a Merchant, and has a Product Type Product Type which belongs to Merchant Type, and has many Products Product which belongs to a Product Type What I want to do is using the products in product model show them to the merchant and the merchant will select or not which products he wants to sell, the question I have is how do I record what products which Merchant has along with that Merchants price? |
How to search array through ransack gem? Posted: 16 Jul 2016 03:14 AM PDT I'm using ransack gem for searching in rails application. I need to search an array of email_ids in User table. Referring to this issue at ransack, i followed the steps and added this to the initializers folder ransack.rb Ransack.configure do |config| { contained_within_array: :contained_within, contained_within_or_equals_array: :contained_within_or_equals, contains_array: :contains, contains_or_equals_array: :contains_or_equals, overlap_array: :overlap }.each do |rp, ap| config.add_predicate rp, arel_predicate: ap, wants_array: true end end In the rails console, if i do like this: a = User.search(email_contains_array: ['priti@gmail.com']) it produces the sql like this: "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"deleted_at\" IS NULL AND (\"users\".\"email\" >> '---\n- priti@gmail.com\n')" and gives error like this: User Load (1.8ms) SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND ("users"."email" >> '--- - priti@gmail.com ') ActiveRecord::StatementInvalid: PG::UndefinedFunction: ERROR: operator does not exist: character varying >> unknown LINE 1: ...RE "users"."deleted_at" IS NULL AND ("users"."email" >> '--- ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. : SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND ("users"."email" >> '--- - priti@gmail.com ') Expected is this query: SELECT "users".* FROM "users" WHERE ("users"."roles" @> '{"3","4"}') What is wrong am i doing? |
Chain Scopes as OR Query Posted: 16 Jul 2016 05:31 AM PDT In model: scope :verified, -> { where(verified: true)} scope :active, -> { where(active: true) } Now, Model.active.verified results as active and verified . How can I chain scopes as OR ? Please note that I don't want to combine both scopes as one like: where("active = ? OR verified = ?", true, true) |
How to access default Rubymine cookies from the browser resources tab? Posted: 16 Jul 2016 02:30 AM PDT I am using rails framework at the back-end and angular.js at the front-end. The rails framework session handling mechanism generates and sends the default session-id to the client. I can see those session-id s in the browser resources tab (shown in the attached image). How do I access these resources in JavaScript? I want to fetch the _myapp1_session session id. Any kind of help is really appreciated. I am trying this for more than 10 hours. Thanks in advance!!! |
rails 4 change database from sqlite3 to pgsql Posted: 16 Jul 2016 01:38 AM PDT I am using ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux], Rails 4.2.4 on cloud 9. i want to change my db from sqlite3 to pgsql. i have some data on sqlite3. my database.yml default: &default adapter: sqlite3 pool: 5 timeout: 5000 development: <<: *default database: db/development.sqlite3 test: <<: *default database: db/test.sqlite3 production: <<: *default database: db/production.sqlite3 I tried taps gem it was asking sqlite3 username and password..i don't know where to find those credentials for sqlite3. Is there any other solution for this problem? |
Elastic search persistence using rails database and mutiple associations Posted: 16 Jul 2016 12:52 AM PDT I want to use ElasticSearch to search with multiple parameters (name, sex, age at a time). what I've done so far is included elastic search in my model and added a as_indexed_json method for indexing and included relationship. require 'elasticsearch/model' class User < ActiveRecord::Base include Elasticsearch::Model include Elasticsearch::Model::Callbacks belongs_to :product belongs_to :item validates :product_id, :item_id, :weight, presence: true validates :product_id, uniqueness: {scope: [:item_id] } def as_indexed_json(options = {}) self.as_json({ only: [:id], include: { product: { only: [:name, :price] }, item: { only: :name }, } }) end def self.search(query) # i'm sure this method is wrong I just don't know how to call them from their respective id's __elasticsearch__.search( query: { filtered: { filter: { bool: { must: [ { match: { "product.name" => query } } ], must: [ { match: { "item.name" => query } } ] } } } } ) end end And In controller def index @category = Category.find(params[:category_id]) if params[:search].present? and params[:product_name].present? @users = User.search(params[:product_name]).records end if params[:search].present? and params[:product_price].present? @users = User.search(params[:product_price]).records end if params[:search].present? and params[:item].present? if @users.present? @users.search(item: params[:item], product: params[:product_name]).records else @users = User.search(params[:item]).records end end end There are basically 3 inputs for searching with product name , product price and item name, This is what i'm trying to do like if in search field only product name is present then @users = User.search(params[:product_name]).records this will give me records but If user inputs another filter say product price or item name in another search bar then it's not working. any ideas or where I'm doing wrong :/ stucked from last 3 days |
Upload Image/Video on S3 through Paperclip is too slow Posted: 16 Jul 2016 05:47 AM PDT I have Ruby on Rails application. In that I used Paperclip for upload image/video and store on AWS S3. When I upload video (My video size is 10 MB) on S3. It will take more then 30 Seconds. How can I speed up the process of uploading. That will take less then 5 Sec. Please help me. Thanks In Advanced. |
Ruby - read each line in file to object and add object to array Posted: 16 Jul 2016 05:09 AM PDT I am very new to Ruby and trying to read each line of a file. I want to create an object called LineAnalyzer using each line and then add that object to an array called analyzers. The code I am trying is Class Solution attr_reader :analyzers; def initialize() @analyzers = Array[]; end def analyze_file() count = 0; f = File.open('test.txt') #* Create an array of LineAnalyzers for each line in the file f.each_line { |line| la = LineAnalyzer.new(line, count) } @analyzers.push la; count += 1; end end end Any help or suggestions would be greatly appreciate!! |
Fetching unique and free time slots of a user from two calendars and displaying the result in a single container using ruby/c++/Java Posted: 16 Jul 2016 01:29 AM PDT I have the response from google calendar as follows: [ { start: "2015-11-01T10:00:00.00+08:00", end: "2015-11-01T11:00:00.00+08:00" }, { start: "2015-11-01T11:00:00.00+08:00", end: "2015-11-01T14:00:00.00+08:00" }, { start: "2015-11-01T15:00:00.00+08:00", end: "2015-11-01T17:00:00.00+08:00" } ] and the response from iCalendar as follows: [ { start: "2015-11-01T12:00:00.00+08:00", end: "2015-11-01T13:00:00.00+08:00" }, { start: "2015-11-01T13:00:00.00+08:00", end: "2015-11-01T14:00:00.00+08:00" }, { start: "2015-11-01T14:00:00.00+08:00", end: "2015-11-01T15:00:00.00+08:00" }, { start: "2015-11-01T15:00:00.00+08:00", end: "2015-11-01T16:00:00.00+08:00" } ] As the time slots [11:00-14:00] from Google overlaps time slots [12:00-13:00] and [13:0014:00] in the iCal response. So, i want to take these two objects and output a unique free time slots( no duplicates and overlaps) and order them chronologically. the output should look like this : OUTPUT: [ { start: "2015-11-01T10:00:00.00+08:00", end: "2015-11-01T11:00:00.00+08:00" }, { start: "2015-11-01T11:00:00.00+08:00", end: "2015-11-01T14:00:00.00+08:00" }, { start: "2015-11-01T14:00:00.00+08:00", end: "2015-11-01T15:00:00.00+08:00" }, { start: "2015-11-01T15:00:00.00+08:00", end: "2015-11-01T17:00:00.00+08:00" } ] I am new to ruby. Any idea how to write in Ruby. Thanks!! |
Specifying validation for specific form in some page Posted: 16 Jul 2016 12:01 AM PDT I have a javascript function that validate a popup form before submit it. Unfortunately it's created to handle one popup form per page only. In my case, i have two different popup forms, so i want to specify what to do and also for which one. $.fn.goValidate = function() { var $form = this, $inputs = $form.find('input:text'); var validators = { email: { regex: /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/ } }; var validate = function(klass, value) { var isValid = true, error = ''; if (!value && /required/.test(klass)) { error = 'This field is required'; isValid = false; } else { klass = klass.split(/\s/); $.each(klass, function(i, k){ if (validators[k]) { if (value && !validators[k].regex.test(value)) { isValid = false; error = validators[k].error; } } }); } return { isValid: isValid, error: error } }; var showError = function($input) { var klass = $input.attr('class'), value = $input.val(), test = validate(klass, value); $input.removeClass('invalid'); $('#form-error').addClass('hide'); if (!test.isValid) { $input.addClass('invalid'); if(typeof $input.data("shown") == "undefined" || $input.data("shown") == false){ $input.popover('show'); } } else { $input.popover('hide'); } }; $inputs.keyup(function() { showError($(this)); }); $inputs.on('shown.bs.popover', function () { $(this).data("shown",true); }); $inputs.on('hidden.bs.popover', function () { $(this).data("shown",false); }); $form.submit(function(e) { $inputs.each(function() { if ($(this).is('.required') || $(this).hasClass('invalid')) { showError($(this)); } }); if ($form.find('input.invalid').length) { e.preventDefault(); $('#form-error').toggleClass('hide'); } }); return this; }; $('form').goValidate(); I'm pretty sure that it's all about this line: $('form').goValidate(); Let's say that the first form id is form_1 and the second form_2. What should i put in this line? Something like this i guess: $('form['form_1]').goValidate(); Hope it was clear, thanks ! |
devise_token_auth - skip_confirmation_notification! not working Posted: 16 Jul 2016 07:29 AM PDT The confirmation mail is sent automatically when a user is created. But I need to send the mail through code manually after completing a few more steps. I can't able to prevent the confirmation mail from sending. User model class User < ActiveRecord::Base include DeviseTokenAuth::Concerns::User devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable before_create :skip_confirmation_notification! Note: If I try to use skip_confirmation! it works perfectly without any flaw. But I don't need that functionality because I want to confirm the users only through the confirmation link sent to their mail. |
Using concat in a class with a helper Posted: 16 Jul 2016 05:44 AM PDT I am writing a helper with the following sort of structure; module SomeHelper def some_task(&block) SomeMethods.new(self, block).some_task end class SomeMethods< Struct.new(:view, :callback) delegate :content_tag, to: :view include ActionView::Helpers::TextHelper def some_task content :div do concat content :div, class: 'a' do Header end concat view.capture(&callback) end end end end The final output should be a div that contains both div.a and the html contained within the helper block in the view. I am getting the following error; undefined local variable or method `output_buffer' for #<SomeHelper::SomeSomeMethods... How do I fix this? |
No comments:
Post a Comment