Tuesday, April 5, 2016

Spree Validation failed: Promotion rule can't be blank | Fixed issues

Spree Validation failed: Promotion rule can't be blank | Fixed issues


Spree Validation failed: Promotion rule can't be blank

Posted: 05 Apr 2016 07:24 AM PDT

I was wondering if spree promotion rules have any permitted params that may be giving me this error. I've added an attribute called :quantity into the promotion rules table which I believe is causing me to get this error. These are the params being passed through when I submit a rule.

 {"utf8"=>"✓",   "_method"=>"put",   "authenticity_token"=>"K27F%39U3@#2JFDOSPU32EF92U3332WEF3#$WF",   "promotion"=>{"match_policy"=>"all",   "promotion_rules_attributes"=>{"43"=>{"id"=>"43",   "product_ids_string"=>"4",   "preferred_match_policy"=>"any"},   "44"=>{"id"=>"44",   "product_ids_string"=>"5",   "quantity"=>"7"}}},   "button"=>"",   "id"=>"3"}  

Custom error redirect, flash notice not working

Posted: 05 Apr 2016 07:23 AM PDT

In a classic Rails app I tried to handle errors with a custom controller redirecting to the root_path with a flash message.

routes:

match "/404", :to => "errors#not_found", :via => :all  match "/500", :to => "errors#internal_server_error", :via => :all  

Error controller:

class ErrorsController < Admin::AdminController    def not_found      redirect_to admin_path, notice: "Sorry, reccord not found"    end      def internal_server_error      redirect_to root_path, notice: "Sorry, something went wrong"    end  end  

The error redirect_to admin_path or root_path (I've tried other paths to be sure it's not related)

The admin path just show a dashboard:

class Admin::StaticController < Admin::AdminController    def dashboard      flash.keep      byebug    end  end  

I tried to add the flash.keep even if there's no multiple redirection. Byebug stops the process to help to see what's happening but flash notice appears nil at this point.

Logs (cleaned a little):

Started GET something_not_possible_to_get  Completed 404 Not Found in 13ms (ActiveRecord: 2.3ms)  ActiveRecord::RecordNotFound  Processing by ErrorsController#not_found as HTML  Redirected to the_path  Started GET "/" (root_path)  ByeBug stopping here and notice is nil  continue just render the page as expected but without the notice  

What I'm trying to achieve is to redirect users getting error (404 or 500) to the root_path or another path, let them know something went wrong with a notification message (flash) but without blocking them on the classic Rails error page. Then I could be able to implement internal errors handling (let say email to the admin/owner of the app for instance).

I tried the keep.flash without success.

Why the notice message is dropped? And why this is happening only with errors (I have a lot of redirect_to with notice that are working fine)?

Pull PDF out of database blob field and save within public/assets

Posted: 05 Apr 2016 07:22 AM PDT

I have a blob column in a table that I know represents pdf documents. I am attempting to write a migration that rips out the pdf documents from that blob field, and saves the actual pdf documents within public/assets. I am using paperclip for attachments.

Here is the error I am getting:

StandardError: An error has occurred, all later migrations canceled: "\xC4" from ASCII-8BIT to UTF-8

Here is my script:

class AddSomeAttachments < ActiveRecord::Migration    def up        SomeModel.all.each do |something|        if something.data.present?          FileUtils.mkdir_p(Rails.root.join('public', 'assets', 'some_models', 'attachment1', "#{something.id}" ))        end      end        SomeModel.all.each do |something|        if something.data.present?          File.open(Rails.root.join('public', 'assets', 'some_models', 'attachment1', "#{something.id}", "#{something.attachment1_file_name}"), "w+") do |file|            file << something.data          end        end      end      end      def down      raise "do not migrate down"    end  end  

I did look at this stack overflow question which asked about the same error message. I did attempt adding encoding: UTF-8 at the top of the file but that did not do anything.

Convert image into base64 using capybara

Posted: 05 Apr 2016 07:00 AM PDT

I'm currently using capybara to run some scrapping tasks as well as site testing. I have been having difficulties in downloading images/files using capybara. All the documentations i found only guides on simple buttons,forms, links interaction.

Would really appreciate it if someone knows how to download/convert images on a webpage into base64 format.

rails two different layout templates in same controller?

Posted: 05 Apr 2016 07:12 AM PDT

I have a PagesController with a layout 'pages.html.erb' specified.

  class PagesController < Spree::StoreController      layout 'pages'      respond_to :html        def lifestyle        render 'lifestyle'      end        def co_step_1        render 'co_step_1'      end        def co_step_2        render 'co_step_2'      end      end  

Is it possible to have an additional method in PagesController that uses a different layout? In other words i want to override the layout 'pages.html.erb' in an additional method.

PG::Connection bad error

Posted: 05 Apr 2016 07:21 AM PDT

I am using rails 4.2.6 and ruby 2.3 to create an application .The database I am using is postgresql . When I am running the rails s and going to localhost:3000 then the error PG::Connection bad is showing . how to fix it ?

sneaker is not receiving messages on heroku - RabbitMQ Bigwig

Posted: 05 Apr 2016 06:34 AM PDT

I am trying to run message queues on heroku. For this I am using RabbitMQ Bigwig plugin.

I am publishing messages using bunny gem and trying to receive messages with sneakers gem. This whole setup works smoothly on local machine.

I take following steps to setup queue

I run this rake on server to setup queue:

namespace :rabbitmq do      desc 'Setup routing'      task :setup_test_commands_queue do        require 'bunny'          conn = Bunny.new(ENV['SYNC_AMQP'], read_timeout: 10, heartbeat: 10)        conn.start          ch = conn.create_channel          # get or create exchange        x = ch.direct('testsync.pcc', :durable => true)          # get or create queue (note the durable setting)        queue = ch.queue('test.commands', :durable => true, :ack => true, :routing_key => 'test_cmd')          # bind queue to exchange        queue.bind(x, :routing_key => 'test_cmd')          conn.close      end    end  

I am able to see this queue in rabbitmq management plugin with mentioned binding.

class TestPublisher    def self.publish(test)      x = channel.direct("testsync.pcc", :durable => true)      puts "publishing this = #{Test}"      x.publish(Test, :persistent => true, :routing_key => 'pcc_cmd')    end      def self.channel      @channel ||= connection.create_channel    end      def self.connection      @conn = Bunny.new(ENV['RABBITMQ_BIGWIG_TX_URL'], read_timeout: 10, heartbeat: 10) # getting configuration from rabbitmq.yml      @conn.start    end  end  

I am calling TestPublisher.publish() to publish message.

I have sneaker worker like this:

require 'test_sync'  class TestsWorker    include Sneakers::Worker    from_queue "test.commands", env: nil      def work(raw_event)      puts "^"*100      puts raw_event      # o = CaseNote.create!(content: raw_event, creator_id: 1)      # puts "#########{o}"      test = Oj.load raw_event      test.execute      # event_params = JSON.parse(raw_event)      # SomeWiseService.build.call(event_params)      ack!    end  end  

My Procfile

web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb  worker:  bundle exec rake jobs:work  sneaker: WORKERS=TestsWorker bundle exec rake sneakers:run  

My Rakefile

require File.expand_path('../config/application', __FILE__)  require 'rake/dsl_definition'  require 'rake'  require 'sneakers/tasks'    Test::Application.load_tasks  

My sneaker configuration

require 'sneakers'  Sneakers.configure  amqp: ENV['RABBITMQ_BIGWIG_RX_URL'],                      log: "log/sneakers.log",                      threads: 1,                      workers: 1    puts "configuring sneaker"  

I am sure that message gets published. I am able to get message on rabbitmq management plugin. But sneaker does not work. There is nothing in sneakers.log that can help.

sneakers.log on heroku :

# Logfile created on 2016-04-05 14:40:59 +0530 by logger.rb/41212  

My code is skipping the View and going into controller directly. ruby on rails

Posted: 05 Apr 2016 06:55 AM PDT

My view

<h1>Return a Book</h1>  <%= form_tag("/orders/returnB", method: "get") do %>    <div class="form-group">      <%= label_tag :ID, "ID" %>      <%= text_field_tag :ID, nil, class: "form-control" %>    </div>    <%= submit_tag "Submit", class: "btn btn-default" %>  <% end %>  

My controller

def returnB    getid = params[:ID]    @order = Order.find(getid)    @order.destroy    respond_to do |format|      format.html { redirect_to orders_url, notice: 'Order was destroyed.' }      format.json { head :no_content }    end  end  

its just going directly to the controller and as my controller could not get the id so it give an error. So i am doing this in my route:

get 'orders/return' => 'orders#returnB'

rspec showing error message

Posted: 05 Apr 2016 06:42 AM PDT

Rspec is showing following error message when i run bundle exec rake. But the tests are running fine. Is this something to worry about or is it safe to ignore??

/home/ubuntu/.rbenv/versions/2.2.3/bin/ruby -I/home/ubuntu/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rspec-core-3.4.4/lib:/home/ubuntu/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rspec-support-3.4.1/lib /home/ubuntu/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rspec-core-3.4.4/exe/rspec --pattern spec/**{,/*/**}/*_spec.rb failed

spec_helper.rb    # This file was generated by the `rails generate rspec:install` command. Conventionally, all  # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.  # The generated `.rspec` file contains `--require spec_helper` which will cause  # this file to always be loaded, without a need to explicitly require it in any  # files.  #  # Given that it is always loaded, you are encouraged to keep this file as  # light-weight as possible. Requiring heavyweight dependencies from this file  # will add to the boot time of your test suite on EVERY test run, even for an  # individual file that may not need all of that loaded. Instead, consider making  # a separate helper file that requires the additional dependencies and performs  # the additional setup, and require it from the spec files that actually need  # it.  #  # The `.rspec` file also contains a few flags that are not defaults but that  # users commonly want.  #  # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration  RSpec.configure do |config|    # rspec-expectations config goes here. You can use an alternate    # assertion/expectation library such as wrong or the stdlib/minitest    # assertions if you prefer.    config.expect_with :rspec do |expectations|      # This option will default to `true` in RSpec 4. It makes the `description`      # and `failure_message` of custom matchers include text for helper methods      # defined using `chain`, e.g.:      #     be_bigger_than(2).and_smaller_than(4).description      #     # => "be bigger than 2 and smaller than 4"      # ...rather than:      #     # => "be bigger than 2"      expectations.include_chain_clauses_in_custom_matcher_descriptions = true      expectations.syntax = [:expect]    end      # rspec-mocks config goes here. You can use an alternate test double    # library (such as bogus or mocha) by changing the `mock_with` option here.    config.mock_with :rspec do |mocks|      # Prevents you from mocking or stubbing a method that does not exist on      # a real object. This is generally recommended, and will default to      # `true` in RSpec 4.      mocks.verify_partial_doubles = true      mocks.verify_doubled_constant_names = true    end    # The settings below are suggested to provide a good initial experience  # with RSpec, but feel free to customize to your heart's content.  =begin    # These two settings work together to allow you to limit a spec run    # to individual examples or groups you care about by tagging them with    # `:focus` metadata. When nothing is tagged with `:focus`, all examples    # get run.    config.filter_run :focus    config.run_all_when_everything_filtered = true      # Allows RSpec to persist some state between runs in order to support    # the `--only-failures` and `--next-failure` CLI options. We recommend    # you configure your source control system to ignore this file.    config.example_status_persistence_file_path = "spec/examples.txt"      # Limits the available syntax to the non-monkey patched syntax that is    # recommended. For more details, see:    #   - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/    #   - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/    #   - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode    config.disable_monkey_patching!    config.expose_dsl_globally = true      # Many RSpec users commonly either run the entire suite or an individual    # file, and it's useful to allow more verbose output when running an    # individual spec file.    if config.files_to_run.one?      # Use the documentation formatter for detailed output,      # unless a formatter has already been configured      # (e.g. via a command-line flag).      config.default_formatter = 'doc'    end      # Print the 10 slowest examples and example groups at the    # end of the spec run, to help surface which specs are running    # particularly slow.    config.profile_examples = 10      # Run specs in random order to surface order dependencies. If you find an    # order dependency and want to debug it, you can fix the order by providing    # the seed, which is printed after each run.    #     --seed 1234    config.order = :random      # Seed global randomization in this process using the `--seed` CLI option.    # Setting this allows you to use `--seed` to deterministically reproduce    # test failures related to randomization by passing the same `--seed` value    # as the one that triggered the failure.    Kernel.srand config.seed  =end  end  

rails_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'  ENV['RAILS_ENV'] ||= 'test'  require File.expand_path('../../config/environment', __FILE__)  # Prevent database truncation if the environment is production  abort("The Rails environment is running in production mode!") if Rails.env.production?  require 'spec_helper'  require 'rspec/rails'  # Add additional requires below this line. Rails is not loaded until this point!    # Requires supporting ruby files with custom matchers and macros, etc, in  # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are  # run as spec files by default. This means that files in spec/support that end  # in _spec.rb will both be required and run as specs, causing the specs to be  # run twice. It is recommended that you do not name files matching this glob to  # end with _spec.rb. You can configure this pattern with the --pattern  # option on the command line or in ~/.rspec, .rspec or `.rspec-local`.  #  # The following line is provided for convenience purposes. It has the downside  # of increasing the boot-up time by auto-requiring all files in the support  # directory. Alternatively, in the individual `*_spec.rb` files, manually  # require only the support files necessary.  #  # Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }    # Checks for pending migration and applies them before tests are run.  # If you are not using ActiveRecord, you can remove this line.  ActiveRecord::Migration.maintain_test_schema!    RSpec.configure do |config|    # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures    config.fixture_path = "#{::Rails.root}/spec/fixtures"      # If you're not using ActiveRecord, or you'd prefer not to run each of your    # examples within a transaction, remove the following line or assign false    # instead of true.    config.use_transactional_fixtures = true      # RSpec Rails can automatically mix in different behaviours to your tests    # based on their file location, for example enabling you to call `get` and    # `post` in specs under `spec/controllers`.    #    # You can disable this behaviour by removing the line below, and instead    # explicitly tag your specs with their type, e.g.:    #    #     RSpec.describe UsersController, :type => :controller do    #       # ...    #     end    #    # The different available types are documented in the features, such as in    # https://relishapp.com/rspec/rspec-rails/docs    config.infer_spec_type_from_file_location!      # Filter lines from Rails gems in backtraces.    config.filter_rails_from_backtrace!    # arbitrary gems may also be filtered via:    # config.filter_gems_from_backtrace("gem name")  end  

rake.rb

#!/usr/bin/env ruby  require_relative '../config/boot'  require 'rake'  Rake.application.run  

Rails devise email authentication error

Posted: 05 Apr 2016 07:07 AM PDT

I am new to rails and i'm using a rails devise template application. When i enter my email and try reset my password, i get the following error: authentication required

enter image description here

What does this mean?

UPDATE: As suggested by trh, the error is coming from secrets.yml Here is what it currently looks like:

development:  admin_name: Ben  admin_email: admin@exmaple.com  admin_password: password  email_provider_username: "username@gmail.com" #eg. ben@gmail.com  email_provider_password: "password"  domain_name: example.com  secret_key_base: #30 digit code  

Is it possible that the error comes from the way i have declared the email provider username and password? does it need to be in the form <%= ENV["GMAIL_USERNAME"] %>?

DB creation in rails using the rake command

Posted: 05 Apr 2016 06:37 AM PDT

I am trying to create a testing DB. I used the following command :

  rake db:schema:create  

also tried various versions of code such as

sudo bundle exec rake db:create  

I keep getting the same error :

rake aborted!  LoadError: no such file to load -- bundler/setup  /home/eshel/test/test_db/config/boot.rb:4:in `<top>'  /home/eshel/test/test_db/config/application.rb:1:in `<top>'  /home/eshel/test/test_db/config/application.rb:1:in `<top>'  /home/eshel/test/test_db/Rakefile:1:in `(root)'  /home/eshel/test/test_db/Rakefile:5:in `(root)'  (See full trace by running task with --trace)  

Tried to install bundles many times but nothing worked so far.

What am I missing ?

Rails 4 current_user (gem devise) acess into model

Posted: 05 Apr 2016 06:29 AM PDT

I would like add condition in my model (ForumsTopic) and i need the current user value.

Here's my ForumsTopic.rb :

class ForumsTopic < ActiveRecord::Base   belongs_to :forum   belongs_to :user   has_one :topic_track, ->(user){where(user_id: current_user.id)}, :class_name=> 'ForumsTrack'   has_many :forums_messages  

on the line with "has_one :topic_track[...] i have one condition with user_id = current_user.id.

But, how i can make that ?

How to import 1M records in batch with ElasticSearch rails?

Posted: 05 Apr 2016 05:55 AM PDT

I want to run a bulk import from my MySQL table to ES - for my model Wine - in my production server. There is 1.5M records.

My model - code for ES gem:

include Elasticsearch::Model  include Elasticsearch::Model::Callbacks    def as_indexed_json(options={})     as_json(only: [:id, :searchable])   end     mapping do    indexes :id, index: :not_analyzed    indexes :searchable  end  

In development, I ran successfully:

bundle exec rake environment elasticsearch:import:model CLASS='Wine' BATCH='100'  

but I have 1000 records only...

Can I run a similar command in prod without issues ? Is there another way ?

I noticed that I need to push the model updated with the code above, else it won't work. The problem is if a user wants to update an object before the bulk import and after my model is changed, there will be an ES issue (DocumentNotFound) - logical. Is-it possible to use a callback to create the ES index if not already created, rather than getting an ES exception ?

What the right way to do that ? Does "elasticsearch:import:model" works in background ?

After fetching CSV file, my terminal output displays only last ~200 items

Posted: 05 Apr 2016 06:36 AM PDT

I am using https://github.com/tilo/smarter_csv gem to read my csv files. On the last line of my code I wrote puts records to see output from the function.

filename = 'db/csv/airports_codes.csv'  options = {    :col_sep => 'tt',    :headers_in_file => false,    :user_provided_headers => [      "id",      "code",      "city",      "country",      "country_code",      "continent",      "coordinate_x",      "coordinate_y"    ]  }  records = SmarterCSV.process(filename, options)    puts records  

However there are so many outputs that my terminal displays only last ~200 items. How do I see others?

These are first 2 items displayed on top of the terminal.

{:id=>4564, :code=>"YEB", :city=>"Bar River", :country=>"Canada", :country_code=>"CA", :continent=>"North America", :coordinate_x=>"\\N", :coordinate_y=>"\\N"}  {:id=>4565, :code=>"YED", :city=>"Edmonton", :country=>"Canada", :country_code=>"CA", :continent=>"North America", :coordinate_x=>"\\N", :coordinate_y=>"\\N"}  

I also want to note that it doesn't let me scroll above that. It acts like this is the first line in terminal and that there was nothing above it. I am using Ubuntu linux.

anchor tag a page in spree rails app

Posted: 05 Apr 2016 05:53 AM PDT

I have a rails app running with spree.

To the header of my app, I want to link the page to a specific page. I am using default spree app and then doing modification on the UI part.

So this is what my header is, <li><a href="#">Black Tea</a></li>

Now I want this to take me to t/categories/clothing this path of default spree.

This page is a partial under spree/shared_products_html.erb.

I am not sure how can I do that.

Please help.

Can't install firebird adapter for ruby

Posted: 05 Apr 2016 05:44 AM PDT

enter image description here

My ruby version: ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]

Bundler version: ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]

I got installed: railsinstaller-3.2.0.exe Firebird-2.5.4.26856_0_x64.exe

I think error is somewhere here:

def read_firebird_registry  require 'win32/registry'  Win32::Registry::HKEY_LOCAL_MACHINE.open('SOFTWARE\Firebird Project\Firebird Server\Instances'   , Win32::Registry::KEY_READ)   do |reg|  return reg.read_s('DefaultInstance') rescue nil   end  end  

But i dont know how to fix it and how to install gem with changes in files of this gem.

Is there any other adapter for firebird databases for ruby?

Rails 4.0.0 foreign key for models

Posted: 05 Apr 2016 05:55 AM PDT

Is this wrong to have that same foreign key for two different models? It's Rails 4.0.0 app so conditions are written like that. I ask because I got some problem with blinks and can't find it.

  has_many :messages, :conditions => {:deleted => false, :subject_h => ''}    has_many :messages_send, :class_name => "Message", :foreign_key => "sender_id", :conditions => ['deleted_sender = ?', false]      has_many :blinks, :conditions => {:deleted => false, :subject_h => ''}    has_many :blinks_send, :class_name => "Blink", :foreign_key => "sender_id", :conditions => ['deleted_sender = ?', false]  

Order, Product and OrdersProduct models associations

Posted: 05 Apr 2016 06:44 AM PDT

I am building a rails app in where I need to have Product and Order models.

I think the logical path is to have another model, called OrdersProduct, since a Order can have many products to be ordered, in which I put a product_id, order_id (matching the two other models) and an amount field.

Well, my problem is how can I access each single product information from my OrdersProduct record?

The point is I can do a belongs_to :product association into my OrdersProduct model, but it doesn't makes any sense to put a has_many :orders_products in my Product model.

Models seems something like this:

class Customer < ActiveRecord::Base    # id    # name    # etc…  end    class Product < ActiveRecord::Base    # id    # name    # etc…  end    class Order < ActiveRecord::Base    # id    # customer_id    # etc…  end    class OrdersProduct < ActiveRecord::Base    # order_id    # product_id    # amount  end  

What's the best way to have access to Order.products and get a collection of products related to the OrdersProduct model?

Rails - Redirection from 2 views to 1 edit_view and back with get-params

Posted: 05 Apr 2016 05:19 AM PDT

I have 2 views, there is on both a edit button. This button redirect to the edit_view. If I submit there the redirect shoul bring me back to the views where i came from. And pass id params back with get in the URL to one of this views.

Model:

localhost:3000/order/list > /order/edit_single_order > localhost:3000/order/list?id=1

localhost:3000/order/administrate > /order/edit_single_order > /order/administrate

The redirection :

    def redirect_to_back_or_default_params(default = root_url, *args)        if request.env['HTTP_REFERER'].present? && request.env['HTTP_REFERER'] != request.env['REQUEST_URI']          redirect_to :back, *args        else          redirect_to default, *args        end      end  

The Controller-redirect :

redirect_to_back_or_default_params administrate_order_path(:provider_id => @cart_item.product.provider.id)  

[unixODBC][FreeTDS][SQL Server]Invalid usage of the option NEXT in the FETCH statement

Posted: 05 Apr 2016 05:46 AM PDT

ActiveRecord::StatementInvalid: ODBC::Error: 37000 (153) [unixODBC][FreeTDS][SQL Server]Invalid usage of the option NEXT in the FETCH statement.: EXEC sp_executesql N'SELECT [employee].* FROM [employee] ORDER BY [employee].[EmployeeKey] ASC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY'

When i am trying to get first and last record of Employee it showing the above error.

How to solve this issue?

Should SessionHelper be replaced by controller concerns in Hartl's 3rd edition tutorial

Posted: 05 Apr 2016 05:46 AM PDT

I'm currently reeding Hartl's 3rd edition tutorial for Rails and I'm wondering if the SessionsHelper should be replaced by a controller concerns. I read that helpers are generally used to provide helper functions to views and in the case of SessionsHelper functions are used accross multiple class but never in views.

I think (but not sure) that concerns appear after this tutorial has been released, so my question ...

Should i try to replace the use of SessionsHelper with a controller concern.

Thanks in advance for your answers.

Jquery Product Quick View

Posted: 05 Apr 2016 05:11 AM PDT

I am developing a rails e-commerce app, I need to add a quick view functionality on the products page, but not able to find any suitable plugin, I found few but they are outdated like (jacklmoore.com/colorbox/example1/) which is good but design is little dull as per today standards, I tried to use (codyhouse.co/demo/product-quick-view/index.html#0) but I think there is a bug in this plug-in. So please if anyone can refer me a plugin for product quick view for rails app or in general. Thanks

When reading CSV files the output is strange

Posted: 05 Apr 2016 05:13 AM PDT

I have a CSV file which looks like this:

1ttAAAttAnaattFrench PolynesiattPFttAustralia and Oceaniatt-17.352606tt-145.509956  2ttAAEttAnnabattAlgeriattDZttAfricatt36.822225tt7.809167  3ttAAFttApalachicolattUnited StatesttUSttNorth Americatt29.7276066tt-85.0274416  4ttAAGtt\NttBrazilttBRttSouth Americatt\Ntt\N  

I use this gem to fetch data: https://github.com/tilo/smarter_csv

This is the code I use to show data in terminal console:

filename = 'db/csv/airports_codes.csv'  options = {    :col_sep => 'tt',  }  records = SmarterCSV.process(filename, options)    puts records  

I put these files in seeds.rb file because I will modify this code later to seed my database with data. This last line of code is there so I can see how it looks like. So I run rake db:seed

And the output is obviously huge because there are around ~5k lines. Now the first problem is that I can't see all of the data in my terminal. When I scroll to the top this is the first item (note that ID is 4674 which means it displayed last ~250 items):

{:"1"=>4674, :aaa=>"YPJ", :anaa=>"Aupaluk", :french_polynesia=>"Canada", :pf=>"CA", :australia_and_oceania=>"North America", :"_17.352606"=>59.2967, :"_145.509956"=>-69.5997}  

How do I see others items?

The second problem is that key names are really weird. How do I rename them, or even better, how do I use arrays instead of hashes?

An efficient way to store monthly recurring data that does not change frequently?

Posted: 05 Apr 2016 05:13 AM PDT

I'm trying to find an efficient way to store monthly recurring data that does not change frequently.

class Fund < ApplicationRecord    has_many :factsheets  end    class Factsheet < ApplicationRecord    belongs_to :fund  end  

A Fund will have a new Factsheet per month.
Each Factsheet have an objective on it (very long text, suppose).
The objective may change each month, but not frequently (say, change once per ~10 months).

Any good way to store the objective?

Option 1:

Put objective into model Factsheet, and it will duplicate a lot.
(store 12 objectives for 12 months, but most of them may be exactly the same)

Option 2:

Make objective a model, then Fund has_many :objectives

class Objective < ApplicationRecord    belongs_to :fund  end  

Objective will have a column :effective_on to indicate: from which month a Fund should use this Objective record on its Factsheet.
(store 2 objectives for 12 months if only changed once)

Option 3:

Better idea?

What is the preferred way of listing multiple wheres?

Posted: 05 Apr 2016 05:07 AM PDT

Which is more efficient (or otherwise preferred): to separate the where conditions by commas like this:

previous_rsvps = Rsvp    .where(user_id: array_of_ids,      waitlist_position: nil,      and so on...)  

or to chain them like this:

previous_rsvps = Rsvp    .where(user_id: array_of_ids)    .where(waitlist_position: nil)    and so on...  

or is it better to use SQL ANDs like this:

query = <<-SQL    user_id IN (array_of_ids)    AND waitlist_position IS NULL    AND so on...  SQL  previous_rsvps = Rsvp.where(query)  

I do have some ? parameters in my query, if that makes any difference.

Get marker infowindow using gmaps4rails

Posted: 05 Apr 2016 04:42 AM PDT

I'm using Rails 4 and gem gmaps4rails. How can I get marker.infowindow in js? Here is my code:

handler = Gmaps.build('Google');  handler.buildMap({ provider: {scrollwheel: false}, internal: {id: 'event-detail-map'}}, function(){    markers = handler.addMarkers([        {            "lat": "<%= @event.location.latitude %>",            "lng": "<%= @event.location.longitude %>",            "infowindow": 'Hello!'        }      ]);    marker = markers[0];    marker.getServiceObject().addListener('mouseover', function () {        marker.infowindow.open(marker.serviceObject.map,   marker.serviceObject);    });      handler.bounds.extendWith(markers);    center = {lat: <%= @event.location.latitude %>, lng: <%=@event.location.longitude %>};      handler.map.centerOn(center);    handler.getMap().setZoom(12);  });  

Console writes me this:

Uncaught TypeError: Cannot read property 'open' of undefined  

I need HAML(Abstract Markup Language) video tutorials and help groups references? [on hold]

Posted: 05 Apr 2016 04:27 AM PDT

I am front end developer more then 2 years experience. I got new project which will be build on HAML & ROR. I didn't work on these technologies. kindly share HAML video tutorials and help groups references & guide me how to become expert?

How to show number of total records for an associated model - Rails 4

Posted: 05 Apr 2016 04:34 AM PDT

I need to be able to display the count for an associated model with specific conditions. I have a Mall model that has_many Shops, a Shop model which belongs_to Mall and has_many Sales, and a Sale model that belongs_to Shop.

Basically what I want to do is to first Iterate through each mall to display the :name of each mall, and then I would like to show how many total Sale records exist for shops belonging to each mall. However, I only want to show the number of Sale records with the following criteria: Sale.where('offer_end >= ?', Date.today).

Im not really sure how to achieve this due to Sales not having a direct connection to Malls. The following code is my best attempt to achieve this but its not working.

<% @malls.each do |mall| %>    <%= mall.name %> - <%= mall.shops.sales.where('offer_end >= ?', Date.today).count %>  <% end %>         

Mall Model

class Mall < ActiveRecord::Base      has_many :mall_shops      has_many :shops, :through => :mall_shops      validates :name, presence: true, uniqueness: true  end  

Shop Model

 class Shop < ActiveRecord::Base      has_many :categorizations      has_many :categories, :through => :categorizations      has_many :mall_shops      has_many :malls, :through => :mall_shops      has_many :sales, dependent: :destroy  end  

Sale Model

class Sale < ActiveRecord::Base      belongs_to :shop  end  

How to get assocated model's attribute values in views ? Rails

Posted: 05 Apr 2016 03:59 AM PDT

I have three models...

models/resident.rb

class Resident < ActiveRecord::Base    belongs_to :hostel    has_many :leaves,dependent: :delete_all    has_one :user,dependent: :delete  end  

models/user.rb

class User < ActiveRecord::Base    belongs_to :resident  end  

models/leave.rb

class Leave < ActiveRecord::Base    belongs_to :resident  end  

Now when I am trying to access the value of leave's attribute in views/leave/show.html.erb I am getting this:

app/views/leaves/show.html.erb

<%= @leaves %>  

out put In Browser :

#<Leave::ActiveRecord_Associations_CollectionProxy:0x007fde611850f0>   

My leave controller looks like : leaves_controller.rb

class LeavesController < ApplicationController      def new      if logged_in?         @leave=Leave.new      else        flash[:info]="Please login to mark a leave"        redirect_to root_path      end    end     def show       @leaves= current_user.resident.leaves     end      def create      @leave=current_user.resident.leaves.create(leave_params)      if @leave.save        flash[:info] = "Leave successfully marked"        redirect_to new_leave_path      else        flash[:danger] = "Something wrong Happened try again"        redirect_to root_path      end    end      private    def leave_params      params.require(:leave).permit(:start_date,:end_date,:destination)    end  end  

Am I making correct leaves for resident and related user (create method)?

Is show method correct ?

and How to assess the user's leaves attribute in show.html.erb of leaves views.

Rails: Which is the most recommended directory to put CSV files?

Posted: 05 Apr 2016 04:02 AM PDT

Which is the best directory to place CSV files which I want to use for database seeding? Is it the tmp ?

I am using this gem: https://github.com/tilo/smarter_csv

No comments:

Post a Comment