Saturday, August 27, 2016

rails 5 db:reset not working | Fixed issues

rails 5 db:reset not working | Fixed issues


rails 5 db:reset not working

Posted: 27 Aug 2016 08:13 AM PDT

I want to reset the database of my rails 5 project, but the rails db:reset command is not working.

errormessage:

Permission denied @ unlink_internal - C:/sites5/dawnrebirth/db/development.sqlite3  Couldn't drop database 'db/development.sqlite3'  rails aborted!  Errno::EACCES: Permission denied @ unlink_internal - C:/sites5/dawnrebirth/db/development.sqlite3  bin/rails:4:in `require'  bin/rails:4:in `<main>'  Tasks: TOP => db:drop:_unsafe  (See full trace by running task with --trace)  

Rails: routes.rb and omitting the controller name

Posted: 27 Aug 2016 08:12 AM PDT

From Hartl's Rails Tutorial Book, some routes for static pages are automatically generated:

Rails.application.routes.draw do    get  'static_pages/home'    get  'static_pages/help'    root 'application#hello'  end  

Why do the 'home' and 'help' routes not have the controller#action?
E.g. get 'static_pages/home', to: 'static_pages_controller#home'

The closest documentation of this I could find was in the the Rails Guides routing page's static segments section.

PostgresSQL dump from Ruby on Rails controller

Posted: 27 Aug 2016 08:04 AM PDT

I have implemented ruby on rails app and I want to have a very easy way to create save points and load them from the view of this app.

For now, before I implement a huge undo-stack, I want to do a SQL dump into a file by a ruby on rails controller method and also load the dumped file back into the database. How can I perform this?

Remove <a> tag from rails "link_to" methdo

Posted: 27 Aug 2016 07:58 AM PDT

I need to remove <a> tag from rails link_to method. Here is current code and result:

<%= link_to "ESP", :locale=>'es'%>  <a href="/es/blog/crazy_page">ESP</p>  

Here is my desired outcome:

/es/blog/crazy_page  

Reason I need this is so I could make "alternate" link tag in header for each language. Can't seem to find this anywhere.

Make Rails 5 API Read-Only

Posted: 27 Aug 2016 07:48 AM PDT

I want to make my Rails 5 API app to be read-only i.e. to accept only GET requests.

Currently I've used scaffold to build the necessary routes & controllers. As the use case requires only reading info, I want the app to accept only GET requests.

Another thing I want to know is how can update the data if the app is made read-only.

get popular records by id in rails

Posted: 27 Aug 2016 06:20 AM PDT

I have a table in my db that records the amount of times the page has been viewed by id.

The table records the event id and what im ideally wanting to do is count how many times the event id shows.

That way i can put the popular events on my homepage

Basically it looks like this

MY table:

ID  1  1  1  2  2  3  3  3  3  

This way the returning result would be something like this:

3 would be first, 1 would be second and 2 would be third.

Then what i can do is each result would populate an each in the show on the view.

Any ideas how to do this?

Thanks!

unable to install Bundle in rubymine 7.1.4

Posted: 27 Aug 2016 05:58 AM PDT

I am unable to run my project in rubymine. when i run command 'rails s', it show me "Run bundle install to install missing gems" then i install bundle then it show me an error "An error occurred while installing rmagick (2.15.4), and Bundler cannot continue." then i install "gem install rmagick -v '2.15.4". but nothing happend. it may be because my rubymine version default selected 2.3.0 but it should be 2.2.3. and i already selected in default setting -> ruby sdk and gems -> rvm ruby-2.2.3 but still i am unable to move to 2.2.3

Please help me to move 2.2.3 version.

Thanks, Rahul

Rails: RSpec fails validations of model subclass

Posted: 27 Aug 2016 05:11 AM PDT

I have a Rails 5 setup where RSpec fails to check validations on model subclass. If I manually build the object in console I am able to see the errors which should prevent the record to be valid.

The base model:

class Article < ApplicationRecord    belongs_to :author, class_name: User      validates :author, presence: { message: "L'utente autore dell'articolo è obbligatorio." }    validates :title, presence: { message: "Il titolo dell'articolo è obbligatorio." }  end  

The model which inherits from Article:

class LongArticle < Article    mount_uploader :thumbnail, LongArticleThumbnailUploader      validates :excerpt, presence: { message: "L'estratto dell'articolo è obbligatorio." }    validates :thumbnail, presence: { message: "L'immagine di anteprima dell'articolo è obbligatoria." }  end  

The factory for these models (FactoryGirl):

FactoryGirl.define do    factory :article do        association :author, factory: :author        title "Giacomo Puccini: Tosca"          factory :long_article do            type "LongArticle"            excerpt "<p>Teatro alla Scala: immenso Franco Corelli.</p>"            thumbnail { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'images', 'unresized-long-article-thumbnail.jpg')) }        end    end  end  

This is the RSpec which doesn't work:

require 'rails_helper'    RSpec.describe LongArticle, type: :model do      describe "is valid with mandatory fields" do      it "should be valid with if all mandatory fields are filled" do        article = FactoryGirl.create(:long_article)        expect(article).to be_valid      end        it "should have an excerpt" do        article = FactoryGirl.create(:long_article)        article.excerpt = nil        expect(article).not_to be_valid      end      it "should have the thumbnail" do        article = FactoryGirl.create(:long_article)        article.thumbnail = nil        expect(article).not_to be_valid      end    end    end  

The first spec pass, the other two don't. I tried to test everything in the console, with the same values, and it works, meaning that the record is invalid as it should be.

Is it possible that with RSpec the validations in the subclass won't work?

Cant verify CSRF token authenticity while creating json and html response

Posted: 27 Aug 2016 05:33 AM PDT

I am using my sessions controller to authenticate user through an API call or on the rails web app. The code works fine for the web app but for the api call I a getting cant verify CSRF token. I have set the
protect_from_forgery with: :null_session as null in my applications controller, but still getting this error. Any idea whats missing?

class Drivers::SessionsController < Devise::SessionsController    after_filter :set_csrf_headers, only: [:create, :destroy]    respond_to :json, :html    def create      password = params[:driver][:password]      email = params[:driver][:email]      driver = email.present? && Driver.find_by(email: email)      if driver.valid_password? password        sign_in driver, store: true        driver.reset_authentication_token!        driver.save        respond_to do |format|        format.html {redirect_to drivers_path}        format.json { render json: JSON.pretty_generate(JSON.parse(driver.to_json)), status: 200 }      end          #render json: driver, status: 200      else        render json: { errors: "Invalid email or password" }, status: 422      end    end    protected    def set_csrf_headers      cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?      end  end   

Here is the error:

Started POST "/drivers/login.json?email=driver@test.com&password=[FILTERED]" for ::1 at 2016-08-27 08:11:03 -0400  Processing by Drivers::SessionsController#create as JSON    Parameters: {"email"=>"apidriver@test.com", "password"=>"[FILTERED]"}  Can't verify CSRF token authenticity  Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)  

My Applications controller file

class ApplicationController < ActionController::Base      #skip_before_action :verify_authenticity_token      before_filter :set_paper_trail_whodunnit      before_action :configure_permitted_parameters, if: :devise_controller?      respond_to :html, :json          # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.    protect_from_forgery with: :null_session    #protect_from_forgery with: :exception          def configure_permitted_parameters      devise_parameter_sanitizer.for(:account_update) { |u|         u.permit(:password, :password_confirmation, :current_password, :first_name, :last_name, :phone_number, :description)       }      devise_parameter_sanitizer.for(:sign_up)  { |u|         u.permit(:email, :password, :first_name, :last_name)     }    end      def after_sign_in_path_for(resource)        if current_driver          drivers_path #your path        end        if current_user          new_booking_path        end      end  end  

RSpec slow when Rails use another Rails DB

Posted: 27 Aug 2016 08:08 AM PDT

I got a strange situation on RSpec when Rails testing.
Normaly by using spring RSpec file taken time is very fast.
But, when using another Rails DB RSpec file taken time is 2 or 3 seconds.
My Rails app use another Rails app database.yml to use the same db.
Why is RSpec so slow? and How do I make RSpec fast?

I confirmed this is happened at Rails4 and Rails5.

Environment
DB PostgreSQL 9.4.5

This is my code.

class Test      def self.test      'test'    end  end  

This is my test code.

require 'rails_helper'      RSpec.describe Test do    describe "Test.test" do      it "test" do        expect(Test.test).to eq 'test'      end    end  end  

This is my database.yml. Two rails app use same yml file.

default: &default    adapter: postgresql    encoding: unicode    pool: 5    development:    <<: *default    database: qserver_development    test:    <<: *default    database: qserver_test  

Rails "alternate" link tag for every language

Posted: 27 Aug 2016 07:02 AM PDT

I can't find how to display full url for every language in HEAD of my html page. This is for "alternate" link tag.

Here is my wrong current solution:

<link rel="alternate" href="/es" hreflang="es-es" />  <link rel="alternate" href="/ru" hreflang="ru-ru" />  

And here is my desired outcome that I can't figure how to make:

<link rel="alternate" href="/es/blog/i_like_coding" hreflang="es-es" />  <link rel="alternate" href="/ru/blog/i_like_coding" hreflang="ru-ru" />  

I tried to use this code, but can't strip away <a> tag. from href itself:

<%= link_to "hi", :locale => 'ru' %>  

result for my unsuccesul try:

<a href="/ru/blog/i_like_coding">hi</a>  

How to insert data in join table based on HABTM association rails 4

Posted: 27 Aug 2016 05:34 AM PDT

Hi I am trying to insert data in join table linked with my 2 other models. The problem is that I am unable to insert data in join table.

Here is my code:

restaurant.rb

module Refinery    module Hebel      class Restaurant < Refinery::Core::BaseModel            validates :title, :presence => true, :uniqueness => true          belongs_to :avatars, :class_name => '::Refinery::Image'          has_many :restaurants_wines          has_many :wines, :through => :restaurants_wines          # To enable admin searching, add acts_as_indexed on searchable fields, for example:        #        #   acts_as_indexed :fields => [:title]        end    end  end  

wine.rb

module Refinery    module Hebel      class Wine < Refinery::Core::BaseModel            validates :title, :presence => true, :uniqueness => true          belongs_to :avatars, :class_name => '::Refinery::Image'          has_many :restaurants_wines          has_many :restaurants, :through => :restaurants_wines          # To enable admin searching, add acts_as_indexed on searchable fields, for example:        #        #   acts_as_indexed :fields => [:title]        end    end  end  

join table - restaurant_wine:

module Refinery    module Hebel      class RestaurantWine < Refinery::Core::BaseModel          belongs_to :wine          belongs_to :restaurant          # To enable admin searching, add acts_as_indexed on searchable fields, for example:        #        #   acts_as_indexed :fields => [:title]        end    end  end  

May I need to do anything in forms or what I need to do in order to insert data in join table?

I have a form of add wine and add restaurant as well. I want to add id of wine in join table with restaurant id

Could anyone please explain?

Ruby special usage of CASE Statement

Posted: 27 Aug 2016 04:50 AM PDT

I've got some piece of code:

variable = ...  case variable  when ~:new    ':new method!'  when ~:lenght    ':size method!'  end  

For o = [] it should go to size case and return ':size method!' For o = String should return ':new method' And this part I know how to implement(my solution below) But it should work with any kind of object. And this part I don't know how to implement. I don't know what is wrong in my code and is it correct? My code:

module AbstractClass    def new; false end;    def size; false end;  end    class Class    include AbstractClass  end    class Array    include AbstractClass    def size; true end;  end    class String    include AbstractClass    def new; true end;  end    class Symbol    include AbstractClass    alias ~ to_proc  end  

Thank you for help!

Configure Mailbox to receive mails from mailgun

Posted: 27 Aug 2016 02:45 AM PDT

Could you help us to configure Mailbox gem(https://github.com/mailboxer/mailboxer) to receive mails from mailgun ?

Some one tried with Mandrill https://github.com/mailboxer/mailboxer/issues/305.

This will help integrate Outgoing and Incoming email system from Rails apps seamlessly and can become killer offer from Mailgun to Rails ecosystem.

Please help us to achieve this.

Thanks, Kiran.

account.rb:17:in `withdraw': undefined method `-' for nil:NilClass (NoMethodErro r)

Posted: 27 Aug 2016 04:47 AM PDT

I am getting error while executing form terminal.

withdraw : undefined method '-'  

I do not understand why. I have tried editing with sublime and notepad++.

class Account      def initialize(name, balance, phone_no)          @name = name          @balance = balance          @phone_no = phone_no      end        def deposit(amount)          @amount += amount      end        def withdraw(amount)          @amount -= amount      end        def display()          puts "Name: " + @name          puts "Phone number: " + @phone_no.to_s          puts "Balance: " + @balance.to_s      end        def transfer(amount, target_account)          @balance -= amount          target_account.deposit(amount)      end        def status          return @balance      end  end  

how to get attached entity via put async android client in rails

Posted: 27 Aug 2016 02:44 AM PDT

I am sending a image from android app to server using put method. I am using the async Android library.

i attach a entity to put request like

client.put(Application.getInstance(), slot.getPutUrl(), fileEntity, CONTENT_TYPE, new AsyncHttpResponseHandler() {  

i am trying to process this image using paperclip in rails in django we can access this file using request.FILES['file'], how can we access this file and pass it on to paperclip using rails ?

Why is my rails engine not being initialized within my host application?

Posted: 27 Aug 2016 02:32 AM PDT

I have a rails engine defined as Blog::Engine. I've included it into another rails application (my host application), by specifying it as a gem dependency, and providing the path.

gem 'sizzle-chisel', path: '../sizzle-chisel'  

I run bundle install and everything looks good.

Then when I run the server, I receive:

uninitialized constant Blog::Engine  

This occurs from within my routes.rb file:

mount Blog::Engine => "/blog"  

Here's the output of bundle install:

...  Using turbolinks 2.5.3  Using devise 3.5.6  Using sizzle-chisel 0.0.1 from source at `../sizzle-chisel`  Using yaml_db 0.4.0  ...  

sizzle-chisel is my engine. So, from looking at the bundler output, I concur that it looks fine so far...

So why does it break when I run my host application? If there is an error with my engine, why is it not explaining that to me at some point? It's simply saying "uninitialized constant", which gives me zero clues as to what the problem might be.

Postgres performance issue in my Rails app

Posted: 27 Aug 2016 03:19 AM PDT

I'm using derailed_benchmark gem to track my app performance:

$ PATH_TO_HIT="/api/v2/feed.json?per_page=30&page=1&category_name=Feed" USER_SERVER=webrick TEST_COUNT=20 bundle exec derailed exec perf:stackprof    ==================================    Mode: cpu(1000)    Samples: 20708 (0.42% miss rate)    GC: 3219 (15.54%)  ==================================       TOTAL    (pct)     SAMPLES    (pct)     FRAME        4720  (22.8%)        4694  (22.7%)     block in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_cache         542   (2.6%)         502   (2.4%)     ActiveSupport::Inflector#underscore         413   (2.0%)         413   (2.0%)     ActiveSupport::PerThreadRegistry#instance         364   (1.8%)         364   (1.8%)     ActiveRecord::QueryMethods#validate_order_args         309   (1.5%)         309   (1.5%)     block in ActiveSupport::Inflector#apply_inflections         282   (1.4%)         282   (1.4%)     ThreadSafe::NonConcurrentCacheBackend#[]         257   (1.2%)         257   (1.2%)     ActiveRecord::Relation#initialize         410   (2.0%)         235   (1.1%)     ActiveRecord::Relation#initialize_copy         229   (1.1%)         229   (1.1%)     ActiveRecord::Delegation::DelegateCache#relation_delegate_class         212   (1.0%)         212   (1.0%)     block in ActiveRecord::Relation::Merger#merge         562   (2.7%)         198   (1.0%)     ActiveRecord::QueryMethods#preprocess_order_args         190   (0.9%)         189   (0.9%)     ActiveRecord::Core::ClassMethods#arel_table         181   (0.9%)         181   (0.9%)     JSON#parse         175   (0.8%)         175   (0.8%)     ActiveRecord::Relation#reset         165   (0.8%)         165   (0.8%)     ActiveRecord::Attribute#initialize         153   (0.7%)         153   (0.7%)     ActiveRecord::Relation#values         151   (0.7%)         151   (0.7%)     ActiveRecord::Inheritance::ClassMethods#base_class         333   (1.6%)         151   (0.7%)     ActiveRecord::Scoping::Default::ClassMethods#build_default_scope         144   (0.7%)         144   (0.7%)     Skylight::Normalizers::ActiveRecord::SQL#extract_rust         142   (0.7%)         142   (0.7%)     ActiveRecord::QueryMethods#joins_values         138   (0.7%)         138   (0.7%)     block (4 levels) in Class#class_attribute         195   (0.9%)         133   (0.6%)     ActiveRecord::DynamicMatchers#respond_to?         158   (0.8%)         121   (0.6%)     ActiveRecord::QueryMethods#where_values=         125   (0.6%)         115   (0.6%)     ActiveRecord::Reflection::AssociationReflection#klass         113   (0.5%)         113   (0.5%)     ActiveRecord::Result#initialize_copy         110   (0.5%)         110   (0.5%)     Arel::Table#initialize         193   (0.9%)         109   (0.5%)     ActiveRecord::ConnectionAdapters::PostgreSQL::Utils#extract_schema_qualified_name         114   (0.6%)         106   (0.5%)     Arel::Nodes::Binary#hash         104   (0.5%)         104   (0.5%)     ActiveRecord::QueryMethods#extending_values          99   (0.5%)          99   (0.5%)     ActiveRecord::QueryMethods#order_values  

How can I fix the "block in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_cache" performance issue?

UPDATE

After running same command with "config.middleware.delete "ActiveRecord::QueryCache" in my config/application.rb the results are:

==================================    Mode: cpu(1000)    Samples: 21116 (0.42% miss rate)    GC: 2213 (10.48%)  ==================================       TOTAL    (pct)     SAMPLES    (pct)     FRAME        5619  (26.6%)        5600  (26.5%)     block in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_cache        2268  (10.7%)        2268  (10.7%)     block in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_no_cache         421   (2.0%)         383   (1.8%)     ActiveSupport::Inflector#underscore         304   (1.4%)         304   (1.4%)     ActiveSupport::PerThreadRegistry#instance         294   (1.4%)         294   (1.4%)     block in ActiveSupport::Inflector#apply_inflections         270   (1.3%)         270   (1.3%)     ThreadSafe::NonConcurrentCacheBackend#[]         245   (1.2%)         245   (1.2%)     ActiveRecord::Relation#initialize         229   (1.1%)         229   (1.1%)     ActiveRecord::QueryMethods#validate_order_args         219   (1.0%)         219   (1.0%)     ActiveRecord::Delegation::DelegateCache#relation_delegate_class         207   (1.0%)         207   (1.0%)     ActiveRecord::Inheritance::ClassMethods#base_class         285   (1.3%)         188   (0.9%)     ActiveRecord::Relation#initialize_copy         184   (0.9%)         184   (0.9%)     ActiveRecord::Attribute#initialize         181   (0.9%)         179   (0.8%)     ActiveRecord::Core::ClassMethods#arel_table         175   (0.8%)         175   (0.8%)     Skylight::Normalizers::ActiveRecord::SQL#extract_rust         165   (0.8%)         165   (0.8%)     block in ActiveRecord::Relation::Merger#merge         147   (0.7%)         147   (0.7%)     block (4 levels) in Class#class_attribute         374   (1.8%)         145   (0.7%)     ActiveRecord::QueryMethods#preprocess_order_args         113   (0.5%)         113   (0.5%)     ActiveRecord::Relation#values         112   (0.5%)         112   (0.5%)     ActiveRecord::QueryMethods#joins_values         171   (0.8%)         109   (0.5%)     ActiveRecord::ConnectionAdapters::PostgreSQL::Utils#extract_schema_qualified_name          99   (0.5%)          99   (0.5%)     Arel::Table#initialize          97   (0.5%)          97   (0.5%)     ActiveRecord::Relation#reset         271   (1.3%)          96   (0.5%)     ActiveRecord::Scoping::Default::ClassMethods#build_default_scope         107   (0.5%)          95   (0.4%)     ActiveRecord::Reflection::AssociationReflection#klass          93   (0.4%)          93   (0.4%)     ActiveRecord::QueryMethods#order_values         125   (0.6%)          93   (0.4%)     ActiveRecord::QueryMethods#where_values=          88   (0.4%)          88   (0.4%)     ActiveRecord::Reflection::ThroughReflection#active_record         106   (0.5%)          87   (0.4%)     Skylight::Trace#start          81   (0.4%)          81   (0.4%)     ActiveRecord::QueryMethods#check_cached_relation          80   (0.4%)          80   (0.4%)     ActiveRecord::QueryMethods#where_values  

UDPATE 2

After running the query with "wall time" mode and not "cpu time" mode, this is the results:

==================================    Mode: wall(1000)    Samples: 41424 (1.92% miss rate)    GC: 3648 (8.81%)  ==================================       TOTAL    (pct)     SAMPLES    (pct)     FRAME        4780  (11.5%)        4718  (11.4%)     block in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_cache        2783   (6.7%)        2783   (6.7%)     block in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_no_cache        1088   (2.6%)        1088   (2.6%)     ActiveSupport::PerThreadRegistry#instance         934   (2.3%)         934   (2.3%)     ThreadSafe::NonConcurrentCacheBackend#[]        1031   (2.5%)         926   (2.2%)     ActiveSupport::Inflector#underscore         739   (1.8%)         739   (1.8%)     block in ActiveSupport::Inflector#apply_inflections         626   (1.5%)         626   (1.5%)     ActiveRecord::Relation#initialize         589   (1.4%)         589   (1.4%)     ActiveRecord::Delegation::DelegateCache#relation_delegate_class         577   (1.4%)         577   (1.4%)     ThreadSafe::NonConcurrentCacheBackend#get_or_default         549   (1.3%)         549   (1.3%)     ActiveRecord::Attribute#initialize         497   (1.2%)         497   (1.2%)     block in ActiveRecord::Relation::Merger#merge         497   (1.2%)         497   (1.2%)     ActiveRecord::QueryMethods#validate_order_args         702   (1.7%)         424   (1.0%)     ActiveRecord::Relation#initialize_copy         419   (1.0%)         417   (1.0%)     ActiveRecord::Core::ClassMethods#arel_table         384   (0.9%)         384   (0.9%)     ActiveRecord::Inheritance::ClassMethods#base_class         383   (0.9%)         383   (0.9%)     block (4 levels) in Class#class_attribute         358   (0.9%)         358   (0.9%)     Skylight::Normalizers::ActiveRecord::SQL#extract_rust         329   (0.8%)         329   (0.8%)     ActiveRecord::Base.logger         321   (0.8%)         321   (0.8%)     rescue in Net::BufferedIO#rbuf_fill         315   (0.8%)         315   (0.8%)     ActiveRecord::Core#update_attributes_from_transaction_state         314   (0.8%)         314   (0.8%)     ActiveRecord::ConnectionAdapters::AbstractAdapter#type_map         795   (1.9%)         298   (0.7%)     ActiveRecord::QueryMethods#preprocess_order_args         284   (0.7%)         284   (0.7%)     Arel::Table#initialize         279   (0.7%)         279   (0.7%)     ActiveRecord::Relation#values         278   (0.7%)         278   (0.7%)     ActiveRecord::Relation#reset         734   (1.8%)         264   (0.6%)     ActiveRecord::Scoping::Default::ClassMethods#build_default_scope         263   (0.6%)         263   (0.6%)     ActiveRecord::QueryMethods#joins_values         394   (1.0%)         258   (0.6%)     ActiveRecord::ConnectionAdapters::PostgreSQL::Utils#extract_schema_qualified_name       15323  (37.0%)         249   (0.6%)     ActiveRecord::Querying#find_by_sql         257   (0.6%)         246   (0.6%)     ActiveRecord::Reflection::AssociationReflection#klass  

I'm building my feed.json using index.json.jbuilder, this is how it looks:

json.battles @battles do |battle|    if (battle.products.size == 2)      battle_results = battle.calculate_results      json.(battle, :id)      vote = battle.votes.find_by(user_id: current_user.id)       json.voted vote.present?      if vote        json.product_voted vote.product.id == battle.products[0].id ? "first" : "second"      end      json.mybattle battle.try(:user).try(:id) == current_user.id      json.user do         username = ""        if (battle.try(:user).try(:nickname).present?)          username = battle.try(:user).try(:nickname)        else          username = battle.try(:user).try(:name).try(:downcase).try(:delete,' ')        end        json.username username        json.user_id battle.try(:user_id)        json.profile_image battle.try(:user).try(:image) || ""        json.full_name battle.try(:user).try(:name) || ""       end      json.votes battle_results[:votes]      json.created_at time_ago_in_words(battle.created_at) + " ago"      json.title battle.title      json.first_product do        first_product = battle.products[0]        json.id first_product.id        json.voted first_product.votes.find_by(user_id: current_user.id).present?        json.percentage battle_results[:percentage_product_one]        # json.percentage_after_voting battle_results[:percentage_after_voting_product_one]        json.name first_product.name        json.price SearchFunctions.convert_currency(first_product.price.to_s, current_user.currency_code, 'USD')        # json.price first_product.price.to_s        json.url first_product.url        if first_product.images["sub"] && first_product.images["sub"].kind_of?(Array)          first_product.images["sub"] =  first_product.images["sub"].first(10)        end        json.images first_product.images        json.manufacturer first_product.manufacturer        json.description first_product.description        json.is_user_saved first_product.saved_products.find_by(user_id: current_user.id).present?        json.saved_count first_product.saved_products.length      end      json.second_product do        second_product = battle.products[1]        json.id second_product.id        json.voted second_product.votes.find_by(user_id: current_user.id).present?        json.percentage battle_results[:percentage_product_two]        # json.percentage_after_voting battle_results[:percentage_after_voting_product_two]        json.name second_product.name        json.price SearchFunctions.convert_currency(second_product.price.to_s, current_user.currency_code, 'USD')        # json.price second_product.price.to_s        json.url second_product.url        if second_product.images["sub"] && second_product.images["sub"].kind_of?(Array)          second_product.images["sub"] =  second_product.images["sub"].first(10)        end        json.images second_product.images        json.manufacturer second_product.manufacturer        json.description second_product.description        json.is_user_saved second_product.saved_products.find_by(user_id: current_user.id).present?        json.saved_count second_product.saved_products.length      end    end  end  

Loading configuration and route.rb twice and produces error

Posted: 27 Aug 2016 02:14 AM PDT

Rails.application.initialize! command in environment.rb loads the files including route.rb twice when executing test using rspec. It works when executing it in production environment and route file is loaded exactly once. What may be the issue. I am using gemset

group :development,:test do    gem "rails-erd"    gem 'letter_opener'    gem 'spring'    gem 'faker'    gem 'pry-rails'    gem 'pry-byebug'    gem 'rspec-rails'    gem 'factory_girl_rails'  end  

PG::UndefinedFunction: ERROR LIKE operator

Posted: 27 Aug 2016 02:48 AM PDT

In my Rails project i get this error, when i trying to make rating.

Error:

PG::UndefinedFunction: ERROR: operator does not exist: integer ~~ integer LINE 1: ...dbacks" WHERE "feedbacks"."user_id" = $1 AND (rating LIKE 5) ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. : SELECT COUNT(*) FROM "feedbacks" WHERE "feedbacks"."user_id" = $1 AND (rating LIKE 5)

Controller Code:

unless @user.feedbacks.count == 0    @rating = ((@user.feedbacks.where("rating LIKE 5").count*5 + @user.feedbacks.where("rating LIKE 4").count*4 +    @user.feedbacks.where("rating LIKE 3").count*3 +    @user.feedbacks.where("rating LIKE 2").count*2   +@user.feedbacks.where("rating LIKE 1").count).to_f / @user.feedbacks.count).round(2)  else    @rating = 0  end  

Can someone help me please?

Validate search form in without model

Posted: 27 Aug 2016 01:55 AM PDT

I have this form in rails, in my view new.html.erb

<%= form_for( @rent , html: { class: 'form-horizontal' }) do |f| %>    <div class="form-group">      <label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">        <%= f.text_field :year, class: 'form-control' %>      </div>        <div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">        <%= f.submit 'Buscar', :class =>"btn btn-sm btn-info btn-flat" %>      </div>      <div class="clearfix"></div>    </div>  <% end %>    <%= render 'shared/error_messages', object: @rent %>  

In my controller I have this

class RentsController < ApplicationController      def new        @rent = RentSearch.new      end        private        def search_params          params.require(:year).permit(:year)        end  end  

In my model, had this code:

class RentSearch      include ActiveModel::Validations      include ActiveModel::Conversion      extend ActiveModel::Naming        attr_accessor :year        validates :year, presence: true      validates :year, length: { is: 4 }  end  

With this code I get this error

undefined method `persisted?' for #

But I made some modifications and not show error, but when submit not display any error and form is empty, I don't know how can solve this.

What is the best way to create a form in rails without model access to database and passing all validations to the controller and verify.

Why is the 'rake routes' command also running the rake db:seed command?

Posted: 27 Aug 2016 07:55 AM PDT

I have some seed data in the seeds.rb file.

I load the seed data using rake db:seed. It load correctly.

I enter some new data into my application all works fine.

Then I run the 'rake routes' command to check out the routes and I see that it runs the rake db:seed command because I can see the output from the seeds.rb file.

Here is my seeds.rb file:

#Seeding the Role table  #  p "Removing existing #{Role.all.count} roles"  Role.destroy_all  p "Creating 3 roles"  [:proofreader, :admin, :super_admin].each do |role|    Role.create( name: role )  end  p "Should have created 3 Roles, roles created: #{Role.all.count}"    #Seed the Employee table    #create super_admin employee  p "Removing existing #{Employee.all.count} employees"  Employee.destroy_all  p "Creating one employee"    super_admin = Employee.new(first_name: "Mitchell", last_name: "Gould", email: "mitchell@provenword.com", paypal_email: "go_mitchell@yayoo.ca", skype_id: "chellgouda", mobile: 66816927867, bachelor_degree: "Science", password: "chokta400",postal_code: "50100",address: "211/195 Soi 27, Sriwalee Klong Chun, T. Mae Hia, A. Muang", province_state: "Chiangmai", country: "Thailand", status: "active", os: "mac", role_ids: [Role.last.id])  super_admin.save!    p "Should have created #{Employee.all.count} employee with name #{Employee.first.first_name}."  

Here is the output from rake routes:

Running via Spring preloader in process 17957  "Removing existing 3 roles"  "Creating 3 roles"  "Should have created 3 Roles, roles created: 3"  "Removing existing 2 employees"  "Creating one employee"  "Should have created 1 employee with name Mitchell."                        Prefix Verb   URI Pattern                            Controller#Action          new_employee_session GET    /employees/sign_in(.:format)           devise/sessions#new              employee_session POST   /employees/sign_in(.:format)           devise/sessions#create      destroy_employee_session GET    /employees/sign_out(.:format)          devise/sessions#destroy             employee_password POST   /employees/password(.:format)          devise/passwords#create         new_employee_password GET    /employees/password/new(.:format)      devise/passwords#new        edit_employee_password GET    /employees/password/edit(.:format)     devise/passwords#edit                               PATCH  /employees/password(.:format)          devise/passwords#update                               PUT    /employees/password(.:format)          devise/passwords#update  cancel_employee_registration GET    /employees/cancel(.:format)            employees/registrations#cancel         employee_registration POST   /employees(.:format)                   employees/registrations#create     new_employee_registration GET    /employees/sign_up(.:format)           employees/registrations#new    edit_employee_registration GET    /employees/edit(.:format)              employees/registrations#edit                               PATCH  /employees(.:format)                   employees/registrations#update                               PUT    /employees(.:format)                   employees/registrations#update                               DELETE /employees(.:format)                   employees/registrations#destroy            new_client_session GET    /clients/sign_in(.:format)             devise/sessions#new                client_session POST   /clients/sign_in(.:format)             devise/sessions#create        destroy_client_session GET    /clients/sign_out(.:format)            devise/sessions#destroy               client_password POST   /clients/password(.:format)            devise/passwords#create           new_client_password GET    /clients/password/new(.:format)        devise/passwords#new          edit_client_password GET    /clients/password/edit(.:format)       devise/passwords#edit                               PATCH  /clients/password(.:format)            devise/passwords#update                               PUT    /clients/password(.:format)            devise/passwords#update    cancel_client_registration GET    /clients/cancel(.:format)              devise/registrations#cancel           client_registration POST   /clients(.:format)                     devise/registrations#create       new_client_registration GET    /clients/sign_up(.:format)             devise/registrations#new      edit_client_registration GET    /clients/edit(.:format)                devise/registrations#edit                               PATCH  /clients(.:format)                     devise/registrations#update                               PUT    /clients(.:format)                     devise/registrations#update                               DELETE /clients(.:format)                     devise/registrations#destroy            quotation_requests GET    /quotation_requests(.:format)          quotation_requests#index                               POST   /quotation_requests(.:format)          quotation_requests#create         new_quotation_request GET    /quotation_requests/new(.:format)      quotation_requests#new        edit_quotation_request GET    /quotation_requests/:id/edit(.:format) quotation_requests#edit             quotation_request GET    /quotation_requests/:id(.:format)      quotation_requests#show                               PATCH  /quotation_requests/:id(.:format)      quotation_requests#update                               PUT    /quotation_requests/:id(.:format)      quotation_requests#update                               DELETE /quotation_requests/:id(.:format)      quotation_requests#destroy                show_dashboard GET    /dashboard(.:format)                   dashboard#show                          root GET    /  

How can I stop Rails from running rake db:seed when I run rake routes?

Rails - ajax response handling

Posted: 27 Aug 2016 01:42 AM PDT

I am sending data by using ajax call to 3rd party api to see if the card supports installment, then I get a response in the payment#new action, I just do not know how to show response on the view.

ajax call;

                $.ajax({                   type: "GET",                    url: "/payments/new",                    dataType: "json",                    data: {card_digit},                   success: function(data) {},                    error: function(jqXHR) {}                  });   

payments#new action

def new  ...  ...  uri = URI.parse("https://...")        https = Net::HTTP.new(uri.host,uri.port)        https.use_ssl = true        req = Net::HTTP::Post.new(uri.path, @headers)            req.body = @body.to_json        res = https.request(req)            puts "Response #{res.code} #{res.message}: #{res.body}"    end  

Then here it returns res.body as json object, I would like to show this on the view I have tried to assign to a variable like @return then use it on the view but no chance, I tried with respond to block but could not manage to do it either.

EDIT

Thank you for the answer!, But now I get error Encoding::UndefinedConversionError ("\xC4" from ASCII-8BIT to UTF-8)

res.body returns;

{"bankId":"13","bankName":"...","cardFamilyId":"..","cardFamilyName":"...","cardThreeDSecureMandatory":"0","merchantThreeDSecureMandatory":"0","result":"1","serviceProvider":"2","supportsInstallment":"1","type":"1"}  

I wrote;

render json: { res_body: res.body }  

and console.log(data) in the success function

why would it happen?

EDIT

I added

render json: { res_body: JSON.parse(res.body) }  

Rails - how to search the console where there is a has_one association

Posted: 27 Aug 2016 01:23 AM PDT

I'm trying to figure out what I need to do to use associations in my views. There is something wrong where the association is a has_one relationship.

I have models called Project and Package. The associations are:

Project has_one :package    Package belongs_to :project  

In the console, I can write:

p = Project.where(id: 26)   

That gives me a project. Then I write:

p.package   

I expect that to give me the associated package. Instead I get a long error message that starts with these lines:

NoMethodError: undefined method `package' for #<Project::ActiveRecord_Relation:0x007fb275c17698>  

I don't know what this message means. I'm especially confused, because I can write:

p = Package.find_by(project_id:26)  

That gives me the right package.

p = Package.find_by(project_id:26)    Package Load (1.8ms)  SELECT  "packages".* FROM "packages" WHERE "packages"."project_id" = $1 LIMIT 1  [["project_id", 26]]   => #<Package id: 25, project_id: 26, created_at: "2016-08-18 23:16:06", updated_at: "2016-08-24 05:11:11", has_gallery: nil>   

Why can't I find the package by writing p.package in the console?

I have seen this post but i haven't understood the gist of what's going on.

Getting Unexpected token with react-rails es6

Posted: 27 Aug 2016 01:17 AM PDT

Rails 5.0.0.1  Ruby 2.3.1  

I would of thought this would have been a presents issue but then again, it works for the person who created the tutorial Im following in conjunction with this. So, nothing fancy:

Application.js

//= require jquery  //= require jquery_ujs  //= require turbolinks  //= cable  //= require_self  //= require react_ujs    window.$ = window.jQuery = global.$ = require('jquery');  var React = window.React = global.React = require('react');  var ReactDOM = window.ReactDOM = global.ReactDOM = require('react-dom');    require('./components');  

Components.js

require( 'babel-polyfill' );  // Manually add components to window and global  // so that react_ujs and react-server can find them and render them.  window.Home = global.Home = require("./components/Home.js").default  // same issue if use *.es6.jsx  

Home.js (or es6.jsx)

import React from 'react';  import ReactDOM from 'react-dom';    class Home extends React.Component {    render() {      return (        <div className="form-control">          Home baby        </div>      )    }  }  export default Home;  

Gemfile

gem "browserify-rails"  gem 'react-rails  

config/application.rb

# Configure Browserify to use babelify to compile ES6  config.browserify_rails.commandline_options = "-t [ babelify --presets [ es2015 ] ]"    unless Rails.env.production?      # Work around sprockets+teaspoon mismatch:      Rails.application.config.assets.precompile += %w(spec_helper.js)        # Make sure Browserify is triggered when      # asked to serve javascript spec files      config.browserify_rails.paths << lambda { |p|          p.start_with?(Rails.root.join("spec/javascripts").to_s)      }  end  

npm

npm install browserify browserify-incremental babelify babel-preset-es2015 --save  

The Unexpected token refers to the first <div>, why?

Rails4 : How to assign a nested resource id to another resource

Posted: 27 Aug 2016 01:08 AM PDT

Model:

order & material
order has_many materials
material belongs_to order

material & user
material has_may users
user belongs_to material

Assume I create a material with id = 20 , order_id = 1

In materials_controller update action, I want to assign material id to specific users.In materials_controller update action I did it like this

    if @material.update_attributes(material_params)        if @material.ready == true          @users = User.where("is_manager = 't'")          @users.each do |user|            user.material_id = @material.id          end        end     end  

But attribute material_id in user did not get changed after the action. Anybody could tell me what cause the failure to pass material id to user ?

Rails - has_many only display per :id

Posted: 27 Aug 2016 05:25 AM PDT

I currently have installed DHTMLxScheduler following the below guide

http://dhtmlx.com/blog/use-dhtmlxscheduler-ruby-rails-part-1-tutorial/

I've been able to successfully create events to my postgresql db although I had to create my own EventsController.

I've currently got the calendar appearing within a project 'show' page and would like to only display the events associated to the project.

I've created an association with events belong_to :projects and has_many: events

my problem is i'm not sure how I can limit this...

below is my code

Events Controller

class EventsController < ApplicationController    def data       events = Event.all         render :json => events.map {|event| {                  :id => event.id,                  :start_date => event.start_date.to_formatted_s(:db),                  :end_date => event.end_date.to_formatted_s(:db),                  :text => event.text              }}     end        def db_action       mode = params["!nativeeditor_status"]       id = params["id"]       start_date = params["start_date"]       end_date = params["end_date"]       text = params["text"]       project_id = self.project.find(:id)         case mode         when "inserted"           event = Event.create :start_date => start_date, :end_date => end_date, :text => text, :project_id => project_id           tid = event.id           when "deleted"           Event.find(id).destroy           tid = id           when "updated"           event = Event.find(id)           event.start_date = start_date           event.end_date = end_date           event.text = text           event.project_id = project_id           event.save           tid = id       end         render :json => {                  :type => mode,                  :sid => id,                  :tid => tid,              }     end    end  

Event Model

class Event < ApplicationRecord      belongs_to :project  end  

Projects Model

class Project < ApplicationRecord      has_many :events        has_attached_file :logo, styles: { medium: "300x300>", thumb: "100x100>" }, :default_url => "***", :s3_protocol => :https      validates_attachment_content_type :logo, content_type: /\Aimage\/.*\Z/  end  

Projects Controller

class ProjectsController < ApplicationController    before_action :set_project, only: [:show, :edit, :update, :destroy]      # GET /projects    # GET /projects.json    def index      @projects = Project.all    end      # GET /projects/1    # GET /projects/1.json    def show    end      # GET /projects/new    def new      @project = Project.new    end      # GET /projects/1/edit    def edit    end      # POST /projects    # POST /projects.json    def create      @project = Project.new(project_params)        respond_to do |format|        if @project.save          format.html { redirect_to @project, notice: 'Project was successfully created.' }          format.json { render :show, status: :created, location: @project }        else          format.html { render :new }          format.json { render json: @project.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /projects/1    # PATCH/PUT /projects/1.json    def update      respond_to do |format|        if @project.update(project_params)          format.html { redirect_to @project, notice: 'Project was successfully updated.' }          format.json { render :show, status: :ok, location: @project }        else          format.html { render :edit }          format.json { render json: @project.errors, status: :unprocessable_entity }        end      end    end      # DELETE /projects/1    # DELETE /projects/1.json    def destroy      @project.destroy      respond_to do |format|        format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_project        @project = Project.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def project_params        params.require(:project).permit(:status, :completed, :description, :priority, :hospital, :name, :code, :capex, :pm, :itpm, :ffe, :start, :pc, :commission, :budget, :logo, :state, :budget_url, :events)      end  end  

config/routes.rb

  match "events/data", :to => "events#data", :as => "data", :via => "get"    match "events/db_action", :to => "events#db_action", :as => "db_action", :via => "get"  

Swapping delivery and address solidus and removing payment steps

Posted: 26 Aug 2016 11:38 PM PDT

i wanted to setup cash on delivery and in store pick as my shipping options. So when the user selects the in store pick up the address is set to store location.

these are the changes i made to order_decorator.rb

Spree::Order.class_eval do   remove_checkout_step :payment    checkout_flow do     go_to_state :delivery     go_to_state :address     go_to_state :confirm     go_to_state :complete   end   end  

when i checkout after adding some items i get unshippable items

do i have to change the code in checkout.rb file

are there any good guides on solidus

Thank you

Rename column, but ThinkingSphinx::SphinxError: unknown column: 'shop_address_lookup'

Posted: 26 Aug 2016 11:51 PM PDT

Using Rails 4, Thinking Sphinx 3.2.0. I recently renamed a column from for_search to address_lookup. The Shop model has the column address_lookup, and I have Country which is associated to Shop model.

Here's my Country index:

ThinkingSphinx::Index.define :state, with: :real_time do    indexes name    indexes shop_address_lookup    ...  end  

I removed the development.sphinx.conf, and ran ts:regenerate. Indexing Shop worked fine, but when it tried to index Country, it kept throwing the following error:

Generating index files for country_core  rake aborted!  ThinkingSphinx::SphinxError: unknown column: 'shop_address_lookup' - REPLACE INTO country_core (id, `sphinx_internal_class_name`, `name`, `country_status`, `shop_address_lookup`  ...  /Users/abc/.rbenv/versions/2.3.1/bin/bundle:23:in `load'  /Users/abc/.rbenv/versions/2.3.1/bin/bundle:23:in `<main>'  Innertube::Pool::BadResource: Innertube::Pool::BadResource  /Users/abc/.rbenv/versions/2.3.1/bin/bundle:23:in `load'  /Users/abc/.rbenv/versions/2.3.1/bin/bundle:23:in `<main>'  ThinkingSphinx::QueryExecutionError: unknown column: 'shop_address_lookup'  ...  /Users/abc/.rbenv/versions/2.3.1/bin/bundle:23:in `load'  /Users/abc/.rbenv/versions/2.3.1/bin/bundle:23:in `<main>'  Mysql2::Error: unknown column: 'shop_address_lookup'  /Users/abc/.rbenv/versions/2.3.1/bin/bundle:23:in `load'  /Users/abc/.rbenv/versions/2.3.1/bin/bundle:23:in `<main>'  Tasks: TOP => ts:regenerate => ts:generate  (See full trace by running task with --trace)  

I only renamed the column, and already updated my index file. What can I do to fix this?

Note: When I rename the index from shop_address_lookup to shop_for_search again, without changing the actual column name, the index works fine.

How to include a Module into Helper and call it with a namespace in a view in Ruby on Rails

Posted: 26 Aug 2016 11:09 PM PDT

So, guys, for example, I have the module N1::M1 and M1 inside folder lib in my project, and I want use it in a view, like this: M1.method_name, but when I define ActionView::CompiledTemplates.include N1 inside ApplicationHelper module, all methods called with a namespace M1 the Rails automatically add the N1 namespace, but not all M1 modules have the N1 namespace. What do I must for use only the M1 as namespace?

No comments:

Post a Comment