Friday, October 7, 2016

How to refresh or change ActiveRecord relationships? | Fixed issues

How to refresh or change ActiveRecord relationships? | Fixed issues


How to refresh or change ActiveRecord relationships?

Posted: 07 Oct 2016 07:50 AM PDT

So I have a RoR app that uses MongoDB. The data has a fairly complex model (there's a lot more, but these are the relevant classes):

class Organization:      has_many :bulletin_inserts      has_many :bulletin_insert_items      has_many :sections    class BulletinInsert < Section      has_many   :bulletin_insert_items      belongs_to :organization, index: true    class BulletinInsertItem      belongs_to :bulletin_insert, index: true      belongs_to :organization, index: true  

Something in the DB got screwed up and now there are a lot of BulletinInsertItems that are listed in the @organization.bulletin_insert_items arrays, but their @bulletin_insert_item.organization attribute is either missing or incorrect.

But when I try and change the attribute in a rake task:

Organization.each do |org|    org.bulletin_insert_items.each do |bii|      if bii.organization != org        bii.update_attributes(organization: org) if bii.organization.present?  

I get an error:

rake aborted!  can't add a new key into hash during iteration  

How can I fix these? Why does Ruby think organization is a new key for the BulletinInsertItem since it's already present in the model?

Is there some conflict since BulletinInsert subclasses Section, and there's a relationship between Organization and both Section and BulletinInsert?

downcase remove duplicates rails save database

Posted: 07 Oct 2016 07:47 AM PDT

I'm trying to do a simple downcase and remove duplicates in rails. Also save to the database.

Tag.all.each do |tag|    tag_name = tag.name.downcase!    tag_name.uniq!    tag.save!  end  

Error

NoMethodError: undefined method `uniq!' for nil:NilClass  

Also tried with pluck

tag_name = Tag.pluck(:name)  tag_name.each do |tag|    name = tag.downcase!    name.uniq!  end  

Error

NoMethodError: undefined method `uniq!' for nil:NilClass  

rails stylesheet_link_tag and image_tag: Object doesn't support this property or method

Posted: 07 Oct 2016 08:05 AM PDT

every time i try to define css file as "stylesheet_link_tag" or image as "image_tag" i got this error:- ExecJS::ProgramError in Demo#index TypeError: Object doesn't support this property or method

  • I have defined my css files in application.css right and it works when using regular html
  • rails version : Rails 5.0.0.1
  • windows: 8.1 64bit

Item deleting itself from Cart - Rails

Posted: 07 Oct 2016 07:31 AM PDT

I'm having an issue with my cart in an e-commerce app. Currently my set up is

Customer logs in to checkout and orders! After the order is completed, the cart is marked as "purchased".

Now here comes the issue, if the customer signs in at a later date to buy something.

When the customer clicks add to cart, the customer's cart gets checked to see if it has been "purchased"; if so, it destroys it and creates a new one.

The issue with that is, the item that was just added to the cart disappears with the old cart; so the customer is presented with an empty cart and has to go back and re-add the item to cart.

Is there a way to avoid this?

Any help would be appreciated. Thanks in advance!

class Customer::CartsController < ApplicationController    before_action :authenticate_user!    def show        if current_user      if current_user.cart.purchased_at          session[:cart_id] = nil      else      @cart = current_user.cart ||= Cart.find_by(session[:cart_id])      end    end   if session[:cart_id].nil?      current_user.cart = Cart.create!(user_id: params[:id])      session[:cart_id] = current_user.cart.id    end   @cart = current_user.cart  end  

The Cart Controller create action

class CartsController < ApplicationController   def create    @cart = Cart.new(cart_params)      respond_to do |format|    if @cart.save      format.html { redirect_to @cart, notice: 'Cart was successfully created.' }      format.json { render :show, status: :created, location: @cart }    else      format.html { render :new }      format.json { render json: @cart.errors, status: :unprocessable_entity }    end  end  end  

The Cart Model

class Cart < ActiveRecord::Base  has_many :line_items, dependent: :destroy  belongs_to :user    def add_product(product_id, size)      current_item = line_items.find_by(product_id: product_id, size: size)      if current_item          current_item.quantity += 1      else          current_item = line_items.build(product_id: product_id, size: size)      end      return current_item  end    def total_price      line_items.to_a.sum { |item| item.total_price }  end  end  

User Model

class User < ActiveRecord::Base   devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable, :invitable,  has_one :cart  after_create :default_cart    def add_products_from_session cart_id  if role == customer?    session_cart = Cart.find cart_id if cart_id  end  if cart && session_cart    session_cart.line_items.each{ |li| self.cart.line_items << li }    session_cart.reload    session_cart.destroy  elsif session_cart    self.cart = session_cart  end    private    def default_cart     self.create_cart    end  end  

Application Controller

def after_sign_in_path_for(resource)      resource.add_products_from_session session[:cart_id]      if resource.customer?        session[:previous_url] || customer_cart_path      end  end  

Line Item controller

def create  product = Product.find(params[:product_id])  @line_item = @cart.add_product(product.id, params[:size])    respond_to do |format|    if @line_item.save      format.html { redirect_to customer_cart_path }      format.json { render :show, status: :created, location: @line_item }    else      format.html { render :new }      format.json { render json: @line_item.errors, status: :unprocessable_entity }    end  end  end  

How can I save the output of an API call to a table in my database?

Posted: 07 Oct 2016 07:31 AM PDT

I am calling data from an API using HTTParty and I am able to output the data in terminal using rails runner. (I am not going to have this data available in a view, I just need to save it in the database for later use). For now my file is lib/referrers.rb

The output is returned like this:

{"id"=>718371286,    "created_at"=>"2016-10-07T13:29:19Z",    "updated_at"=>"2016-10-07T13:29:20Z",    "tracking_code"=>"fd8382a2-2ec3-4377-9463-25f8d2e13fd1",    "lead"=>nil,    "url"=>     {"id"=>90935841,      "url"=>"http://m.facebook.com"},    "referrer"=>{"id"=>4786600, "url"=>"http://m.facebook.com"},    "affiliate"=>nil,    "campaign"=>nil,    "search_term"=>nil}  

I would like to separate the data and save it as text, the columns in my table would be:

uri_id, tracking_code, lead, url, referrer, affiliate, campaign, search_term, created_at, updated_at

What I would like to know is how can I go about saving the data to my database?

Also can this be achieved without having to start the rails server every time?

Can't connect to my app with facebook

Posted: 07 Oct 2016 07:41 AM PDT

On rails 4, I am using devise to authenticate my users and I am also adding a facebook authentication... I've followed thisdocumentation and I set up in my config var on heroku.

 config.omniauth :facebook, "APP_ID", "APP_SECRET", callback_url: "CALLBACK_URL"  

Now when I am on my url if I click on sign up with facebook link I arrive on facebook login page (as I am logged out from facebook) and when I clcik login I am redirected to this: What is wrong? Thanks for your help :)

enter image description here

here are my logs

at=info method=GET path="/users/auth/facebook/callback?code=AQBSQ125f8npBttjqtAZ4uN9M2-u_DaHqMdp2LJadvBUESXOP_u7q-OL_U0XDlrk836GuXu63OPXAerDTsG7xwgXSg93VgSEMxjs-L733DCsQ1zpoPBMxUgGIQLFb3QxQIqU544ymZuNsDEhdofUj58hrcjOOpg9fEZjQb3lvZqCd34mPt2MVPjQJJAMoe1Vo5n0Y1ozyhYjpSH2DfKTHsmK38ba_7TD8I48M47g0rItI55vvLkrogHLnpgf_NlHjgeHMXldPzsKgEybRM2ouR8S6zKNLsWRJlQ_TbJe_sYuRU85WNoJeAlRrHW-iiw1N4XHIxO2W-JTMG71jwqelSjrPM6c1kPzJbNu-zxjo1vNpQ&state=8a8f36fdd32be2f5931f05ac9176c6f5f5412ef9a8f84eeb" host=duclostutos.herokuapp.com request_id=7968a919-2170-4030-8a32-87d64299e5bf fwd="92.171.113.21" dyno=web.1 connect=0ms service=939ms status=404 bytes=1829  

I could have a problem with my routes....

Rails.application.routes.draw do      devise_for :users, only: :omniauth_callbacks, controllers: {omniauth_callbacks: 'users/omniauth_callbacks'}      scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do        get "/best_voted", to: "tutos#best_voted"      resources :tutos      namespace :users do        resources :tutos      end        resources :tutos, only: [:show]        resources :tutos do        member do          put "like", to: "tutos#upvote"        end      end      as :user do      get     "/register",  to: "devise/registrations#new", as: :register      get     "/login",     to: "devise/sessions#new", as: :login      get     "/logout",    to: "devise/sessions#destroy", as: :logout      get     "/account",   to: "users#show", as: :account      get     "/login" ,    to: "devise/sessions#new", as: :new_user_session      post    "/login" ,    to: "devise/sessions#create", as: :user_session      delete  "/logout" ,   to: "devise/sessions#destroy", as: :destroy_user_session    end        devise_for :users, skip: [:sessions, :omniauth_callbacks]        resources :users        root "home#landing"    end    get '*path', to: redirect("/#{I18n.default_locale}/%{path}")    get '', to: redirect("/#{I18n.default_locale}")  end  

How do I catch the "Error during processing: buffer error" in Ruby when getting a web page?

Posted: 07 Oct 2016 07:04 AM PDT

I'm using Rails 4.2.7 and this code to get a webpage through a SOCKS proxy …

  begin      …      res1 = Net::HTTP.SOCKSProxy('127.0.0.1', 50001).start(uri.host, uri.port) do |http|        puts "launching #{uri}"        resp = http.get(uri)        status = resp.code        content = resp.body        content_type = resp['content-type']        content_encoding = resp['content-encoding']      end      …  rescue OpenURI::HTTPError => ex      …  rescue SocketError, Net::OpenTimeout => e     …  

Occasionally, I get an error on the line "rest = http.get(uri)"

Error during processing: buffer error  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/response.rb:364:in `finish'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/response.rb:364:in `finish'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/response.rb:266:in `ensure in inflater'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/response.rb:265:in `inflater'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/response.rb:281:in `read_body_0'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/response.rb:202:in `read_body'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:1157:in `block in get'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:1446:in `block in transport_request'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http/response.rb:163:in `reading_body'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:1445:in `transport_request'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:1407:in `request'  /Users/mikeb/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/net/http.rb:1156:in `get'  /Users/mikeb/Documents/workspace/runtrax/app/helpers/webpage_helper.rb:99:in `block in get_content'  

How do I catch this error? You see the types of errors I'm catching above but I don't know how to catch the particular error I'm getting. My intention is to retry if such an error occurs.

How can I display in rails "only" hours and seconds using simple_form_for?

Posted: 07 Oct 2016 06:46 AM PDT

I am quite new in rails but I could not find an answer for this.

I have the column start defined as datetime type. However, when displaying the form in the view, I want only to see the hours and seconds (and hide the year, month and day) fields.

<%= simple_form_for @availability do |f| %>     <%= f.input :start %>     <%= f.button :submit, class: "btn btn-primary wide-btn" %>  <% end %>  

How can I do this?

Rails 5 - download a paperclip attachment

Posted: 07 Oct 2016 06:21 AM PDT

In the app I am building to learn RoR, I want to automatically download an attached pdf. Attached with Paperclip. Then to get the pdf properties using pdfinfo.

In my annotation.rb model I attach using

has_attached_file :file,      styles: { large: "600x600>", medium: "500x500>", thumb: "150x150#" },      default_url: "/images/:style/missing.png"  

In my AnnotationsController

    require 'pdfinfo'      pdfinfo = Pdfinfo.new('@annotation.file.path')      page_count = pdfinfo.page_count  

this throws an error

Pdfinfo::CommandFailed in AnnotationsController#pdf pdfinfo -f 0 -l -1 -enc UTF-8 @annotation.file.path

What does this error mean and how can I get the file to be read? I learned about downloading using send_file, but have not succeeded.

Array as a condition for find_or_create_by in Rails

Posted: 07 Oct 2016 06:20 AM PDT

I have something like this:

types = ['landline', 'cell']  Phone.find_or_create_by(person_id: 1, type: types) do |record|   record.number = '0'  end  

This doesn't work. New records don't get created. But when I rewrite it to look like this:

types = ['landline', 'cell']  types.each do |type|   Phone.find_or_create_by(person_id: 1, type: type) do |record|    record.number = '0'   end  end  

it works.

Any ideas why find_or_create_by doesn't work with array as a condition?

Replacing partial with AJAX in Rails 4: no errors and no updated data

Posted: 07 Oct 2016 05:37 AM PDT

For the following I'm not receiving any errors and my list-partial is being loaded again after executing the like_oneliner method. But the changed data (oneliner.users.count and the if/else for !joined(oneliner) are not refreshing) isn't showing.

I'm trying to change a button class with an upvote and downvote and try to use the build-in AJAX functionality for it.

models/campaign.rb

belongs_to :user  has_many :oneliners  has_many :general_connections  

models/oneliner.rb

has_many :general_connections  has_many :users, through: :general_connections  belongs_to :campaign  

models/general_connection.rb

belongs_to :oneliner  belongs_to :user  belongs_to :campaign  

models/user.rb

has_many :general_connections  has_many :oneliners, through: :general_connections  has_many :campaigns  

controllers/general_connection.rb

def like_oneliner    @oneliner = Oneliner.find(params[:oneliner_id])    current_user.general_connections.create(oneliner: @oneliner)    respond_to do |format|      format.html { redirect_to :back }      format.js    end  end    def unlike_oneliner    @general_connection = GeneralConnection.where("oneliner_id = ? AND user_id = ?", params[:oneliner_id], current_user.id).first    @oneliner = @general_connection.oneliner      @general_connection.destroy    respond_to do |format|      format.html { redirect_to :back }      format.js    end  end  

views/campaigns/show.html.erb

<div class="row">      <ul class="collection">          <% @oneliners.each do |oneliner| %>               <%= render partial: 'oneliners/list', locals: { oneliner: oneliner } %>          <% end %>      </ul>  </div>  

views/oneliners/_list.html.erb

<li class="collection-item avatar">    <i class="circle black"><%= oneliner.users.count %></i>    <span class="title"><%= oneliner.title %></span>    <p><%= timeago_tag oneliner.created_at, :nojs => true, :limit => 100.days.ago %> / <%=t 'list.employee' %><%= oneliner.user.name %>    </p>      <% if !joined(oneliner) %>      <%= form_tag(onelinerlike_path, remote: true) do %>        <%= hidden_field_tag 'oneliner_id', oneliner.id %>          <%= button_tag 'thumb_up', id: "#{ dom_id(oneliner) }", class: "secondary-content material-icons grey-text", style: "background-color:white;border:none;" %>      <% end %>    <% else %>      <%= form_tag(onelinerunlike_path, remote: true) do %>        <%= hidden_field_tag 'oneliner_id', oneliner.id %>        <%= button_tag 'thumb_up', id: "#{ dom_id(oneliner) }", class: "secondary-content material-icons orange-text", style: "background-color:white;border:none;" %>      <% end %>    <% end %>  </li>  

views/general_connection/like_oneliner.js.erb

$('#<%= dom_id(@oneliner) %>').replaceWith(<%= j render partial: 'oneliners/list', locals: {oneliner: @oneliner} %>");  

The like and unlike methods do works, and I see a small change in the Timeago string (It changes for example from 2 months in 2 months ago), but that's it. The oneliner.users.count and the if/else for !joined(oneliner) only show the new data when I refresh the page.

Can anyone help me out?

Duplicate images uploaded with Dragonfly

Posted: 07 Oct 2016 07:10 AM PDT

I would like to copy a record that has_many :pictures. Copying the record is a no brainer, but copying the Picture records is something else.

  • The Picture record has a link to a Post
  • Picture has an attribute (for Dragonfly) that is image_uid that contains a string like 2016/08/17/3chjxpz97o_tfss_05bbc7ac_a432_4408_bf6e_a0fa3dc4630d_animage.jpeg

The image is stored on an AWS S3 server. From the server perspective I think this does

  • Download the image (original record image_uid) to the server
  • Attach the image to the new Picture record
  • Reupload the image to AWS
  • Is there a method that just copies it on AWS, gives you the new image_uid so I can set it manually on the new record?

Thx

Debugging memory leak in Ruby on Rails background worker

Posted: 07 Oct 2016 05:27 AM PDT

I've noticed that my Ruby on Rails app seems to have a memory leak which creeps up to Heroku's 512mb limit over a 12 – 24 hour period:

enter image description here

I've used Siege to hit the Puma server with a lot of requests and haven't noticed that affecting memory. The app itself is pretty basic, so I am pretty sure the problem lies with the background workers instead.

Here's my clock.rb file which schedules the background workers:

require 'clockwork'  require './config/boot'  require './config/environment'    module Clockwork    configure do |config|      config[:tz] = 'UTC'      config[:max_threads] = 128      config[:thread] = true    end    every(10.minutes, 'Start studies') { StartStudiesWorker.perform_async }    every(10.minutes, 'Finish studies') { FinishStudiesWorker.perform_async }    every(5.minutes, 'Send questions') { EnqueueQuestionsWorker.perform_async }    every(5.minutes, 'Check sent sms status') { CheckSmsStatusWorker.perform_async }    every(1.day, 'Send random questions', at: '00:15') { EnqueueRandomQuestionsWorker.perform_async }  end  

And the Puma configuration file, with comments removed:

threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i  threads threads_count, threads_count  workers ENV.fetch("WEB_CONCURRENCY") { 2 }    port ENV.fetch("PORT") { 3000 }  environment ENV.fetch("RAILS_ENV") { "development" }  preload_app!  plugin :tmp_restart  

I've done a bit of research already and noticed that most articles & questions are about debugging memory leaks in the main app, not necessarily background workers. So I guess my questions are:

  • Do my configuration files for Clock and Puma look okay?
  • What's the best place to start debugging the background workers?

Filterrific and Globalize

Posted: 07 Oct 2016 06:47 AM PDT

It appears as if filterrific does not take content in translation tables into account (Globalize).

Is there anyway to search translation tables as well? My setup works perfectly well if the content is in the actual model. However, once the fields are empty and only entered in the translation table no results are being displayed (obviously).

My Model:

class Manual < ApplicationRecord    translates :title, :content, :teaser, :slug      extend FriendlyId    friendly_id :title, :use => :globalize      belongs_to :user    belongs_to :support_category    has_many :manual_faqs    has_many :faqs, :through => :manual_faqs      validates :title, presence: true    validates :content, presence: true    validates :user_id, presence: true      update_index('manuals#manual') { self }      filterrific(        default_filter_params: { sorted_by: 'created_at_desc' },        available_filters: [            :sorted_by,            :search_query,            :with_user_id,            :with_created_at_gte        ]    )      scope :with_user_id, lambda { |user_ids|      where(user_id: [*user_ids])    }      scope :search_query, lambda { |query|      # Searches the students table on the 'first_name' and 'last_name' columns.      # Matches using LIKE, automatically appends '%' to each term.      # LIKE is case INsensitive with MySQL, however it is case      # sensitive with PostGreSQL. To make it work in both worlds,      # we downcase everything.      return nil  if query.blank?        # condition query, parse into individual keywords      terms = query.downcase.split(/\s+/)        # replace "*" with "%" for wildcard searches,      # append '%', remove duplicate '%'s      terms = terms.map { |e|        ('%' + e.gsub('*', '%') + '%').gsub(/%+/, '%')      }      # configure number of OR conditions for provision      # of interpolation arguments. Adjust this if you      # change the number of OR conditions.      num_or_conds = 2      where(          terms.map { |term|            "(LOWER(manuals.title) LIKE ? OR LOWER(manuals.content) LIKE ?)"          }.join(' AND '),          *terms.map { |e| [e] * num_or_conds }.flatten      )    }      scope :sorted_by, lambda { |sort_option|      # extract the sort direction from the param value.      direction = (sort_option =~ /desc$/) ? 'desc' : 'asc'      case sort_option.to_s        when /^created_at_/          # Simple sort on the created_at column.          # Make sure to include the table name to avoid ambiguous column names.          # Joining on other tables is quite common in Filterrific, and almost          # every ActiveRecord table has a 'created_at' column.          order("manuals.created_at #{ direction }")        else          raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }")      end    }      scope :created_at_gte, lambda { |reference_time|      where('manuals.created_at >= ?', reference_time)    }      def self.options_for_sorted_by      [          ['Date received (newest first)', 'created_at_desc'],          ['Date received (oldest first)', 'created_at_asc']      ]    end  end  

My Controller:

  def index      @filterrific = initialize_filterrific(          Manual,          params[:filterrific],          select_options: {              sorted_by: Manual.options_for_sorted_by,              with_user_id: User.options_for_select          }      ) or return        @manuals = @filterrific.find.page(params[:page])        respond_to do |format|        format.html        format.js      end      rescue ActiveRecord::RecordNotFound => e      # There is an issue with the persisted param_set. Reset it.      puts "Had to reset filterrific params: #{ e.message }"      redirect_to(reset_filterrific_url(format: :html)) and return      #respond_with(@references)    end  

Searchkick different reindex results when not reindex all records

Posted: 07 Oct 2016 06:54 AM PDT

Im using searchkick.

Product.reindex  

This will reindex all the records, and it will works if I search with:

Product.search "*", load: false  

or

Product.search "something", load: false  

But for development purpose only, I only want to for example, 10 records only. So I did this:

Product.take(10).each do |p| p.reindex end  

But it won't work with the search method like I did before.

My questions is:

  • How to reindex only a view records? not all the records.

{"code": 400, "error_type": "OAuthException", "error_message": "Redirect URI does not match registered redirect URI"} in Rails

Posted: 07 Oct 2016 05:13 AM PDT

I am having a photo upload scenario where when I click on link, it has to goto Instagram and upload pictures from there. But I am facing the following issue:

{"code": 400, "error_type": "OAuthException", "error_message": "Redirect URI does not match registered redirect URI"}

This is the redirected url when I click on link :

https://www.instagram.com/oauth/authorize/?client_id=CLIENT_ID&redirect_uri=http://localhost:3000/instagram/callback/?edit=&response_type=code   

This is my code:

routes.rb:

get "/instagram/callback" => "photos#instagram_callback"  

photos_controller:

class PhotosController < ApplicationController    before_filter :check_for_errors, :only => [:instagram_callback]    def instagram_callback      response = Instagram.get_access_token(params[:code], :redirect_uri => Rails.application.config.custom.domain_url + 'instagram/callback/?edit=' + (params[:edit].present? ? params[:edit] : ''))      oauth = OauthAccessToken.find_or_create_by_provider_and_user_id('instagram', current_user.id)      oauth.access_token = response.access_token      oauth.save      if params[:edit].present?        redirect_to edit_user_report_path(current_user, params[:edit], :ig => true)      else        redirect_to new_user_report_path(current_user, :ig => true)      end    end  end  

views/_photos.html.erb:

<% if @instagram_oauth.nil? %>    <%= link_to '', Instagram.authorize_url(:redirect_uri => Rails.application.config.custom.domain_url + 'instagram/callback/?edit=' + (params[:id].present? ? params[:id] : ''))%>  <% end %>  

Please help.

rails - shouldn't I use default values in rails migration

Posted: 07 Oct 2016 06:12 AM PDT

I am not sure whether I should ask this question on SO or not. But I have to as I don't have clear idea about my doubt. I was told not to set default values in rails migrations and use null values instead in a code review by our CTO. And his explanation is like this once the database gets huge enough, migrations with defaults runs slow and may throw database timeout errors. But I think at the database level it is fast enough to execute as its an initial setup of things. Am I right?

Concatenate/append bitcoin address to image_tag source Rails

Posted: 07 Oct 2016 04:07 AM PDT

I have a hash that contains a bitcoin address. The hash looks like this:

{"status"=>"success", "data"=>{"user_id"=>2, "address"=>"2NE9LK7LGKr9dStvxpF64ucKyoywnfcLd1W", "label"=>"slesle91", "available_balance"=>"0.00000000", "pending_received_balance"=>"0.00000000"}}  

I can display the bitcoin address via:

<%= @address["data"]["address"] %>  

How can I add this to an image_tag to get a url like this that create a qr code:

<%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl="2NE9LK7LGKr9dStvxpF64ucKyoywnfcLd1W" %>  

So I am looking for a solution to do something similar to:

%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl="<%= @address["data"]["address"] %>" %>  

Any comment or assistance will be greatly appreciated.

Jekyll: Error: Site could not be built, wrong date format

Posted: 07 Oct 2016 05:26 AM PDT

When I run this in my command line:

$ bundle exec jekyll serve  

I get this error:

Invalid date '': Document 'vendor/cache/gems/jekyll-3.3.0/lib/site_template/_posts/0000-00-00-welcome-to-jekyll.markdown.erb' does not have a valid date in the YAML front matter.

I have updated my gems and installed Xcode. But I still get this error. I run this on: Macbook, macOS Sierra, 10.12.

Can you help?

How can I have the different attributes in different columns using Active admin download csv option?

Posted: 07 Oct 2016 03:36 AM PDT

I'm using Active Admin download to csv option but I get the attributes all in one column. How can I have them in different columns?

How to filter a field from a many-to-many relationship but avoid to cache the results of relationships?

Posted: 07 Oct 2016 04:40 AM PDT

Let's say I have the following models:

class User < ActiveRecord::Base    as_many :role_users    as_many :roles, through: :role_users  end    class RoleUser < ActiveRecord::Base    belongs_to :role    belongs_to :user  end    class Role < ActiveRecord::Base    has_many :role_users    has_many :users, through: :role_users  end  

And i need to find all users who belongs to passenger role.

> r1 = Role.create(:name ="passenger")  > r2 = Role.create(:name ="driver")  >   > u1 = User.create(:name ="Bob")  > u2 = User.create(:name ="Tom")  >   > u1.roles.push r1, r2  > u2.roles.push r1  >   > passengers = User.includes(:roles).where("roles.name": "passenger")  # To find all users who belongs to `passenger` or `driver` role  # passengers = User.includes(:roles).where("roles.name": %w(passenger, driver))    > passengers[0].roles.size  # This is correct  => 1  > passengers[1].roles.size  # This is incorrect  => 1  

It seems to load from cached results.

To reload the cache, it works.

> passengers[1].roles(true).size  # This is correct  => 2  

Is there a better way to do this?


I found a better way to do this:

> users = Role.where(:name => "passenger").take.users  > passengers[0].roles.size  => 1  > passengers[1].roles.size  => 2  

But how to find all users who belongs to passenger or driver role in this way?

Conditional for Nested Attribute?

Posted: 07 Oct 2016 05:14 AM PDT

How can I create a conditional where if the dueler is the current_user then it'll list the current_user's challenges and if the dueler is @user then it'll list the @user's challenges?

duels_controller

def new    @user = User.find(params[:challenge_daddy])    @duel = Duel.new    @duel.duelers << Dueler.new(user_id: current_user.id, user_name: current_user.name, user_last_name: current_user.last_name)    @duel.duelers << Dueler.new(user_id: @user.id, user_name: @user.name, user_last_name: @user.last_name)    @current_user_challenges = current_user.challenges.order(:created_at)    @challenged_user_challenges = @user.challenges.order(:created_at)    respond_with(@duel)  end  

duels/_form.html.erb

<%= simple_form_for(@duel) do |f| %>    <%= f.fields_for :duelers do |dueler| %>      <%= render 'dueler_fields', :f => dueler %>    <% end %>    The loser will <%= f.text_field :consequence %>.    <%= f.submit %>  <% end %>  

duels/_dueler_fields.html.erb

<%= f.select :user_id, User.order(:name).map { |user| [user.full_name, user.id] }, include_blank: true, id: "change-challenge-options" %> will  <%= collection_select(:dueler, :challenge_id, # @challenged_user_challenges or @current_user_challenges  , :id, :full_challenge, include_blank: true) %>  

How do I create a conditional so that if the :user_id is equal to the current_user then @current_user_challenges will show in collection_select and if :user_id is equal to @user then @challenged_user_challenges will show?

Issue with saving token in rails

Posted: 07 Oct 2016 03:16 AM PDT

I am trying to add api authentication to my existing project. For that I am using devise_token_auth gem. I have added a column tokens in user for saving token .I am following the code in github. But following code is generating issue

IndexError (string not matched):  app/controllers/devise_token_auth/sessions_controller.rb:36:in `[]='  app/controllers/devise_token_auth/sessions_controller.rb:36:in `create'  

Code is

@client_id = SecureRandom.urlsafe_base64(nil, false)  @token     = SecureRandom.urlsafe_base64(nil, false)  @resource.tokens[@client_id] = {    token: BCrypt::Password.create(@token),    expiry: (Time.now + DeviseTokenAuth.token_lifespan).to_i  }  

When I remove indexing it worked fine ie,[@client_id]. But the tokens field contains value

{:token=>"$2a$10$yPrhdc.9Tv7AQotIK0be7Ogcxpp1VjlSa/4JyGPaz6o8Gtm9M77wa", :expiry=>1477042703}  

I am doing token based authentication for the first time. Please correct me, if I am doing something wrong

Render Dragonfly images in PDF using wicked-pdf

Posted: 07 Oct 2016 04:10 AM PDT

I am trying to render a pdf of my model containing images stored with dragonfly using wkhtmltopdf but I can't get it to work. The html page renders fine when I use the debug option for wkhtmltopdf but the pdf itself just gets an empty box where the image should go. So far I've only found two sites where this is brought up (a german blog and a google forum thread), but neither solution solved it for me. My suspicion is that I should use absolute paths to the image files, which is suggested in the blog, but when I try that solution the server gets stuck at:

Rendered images/show.pdf.erb (19.9ms)   "***************[\"/home/oskar/.rbenv/versions/2.2.3/bin/wkhtmltopdf\",  \"-q\", \"--encoding\", \"utf8\", \"--orientation\", \"Landscape\",   \"file:////tmp/wicked_pdf20161007-8095-1nlruhe.html\", \"/tmp  /wicked_pdf_generated_file20161007-8095-1f6vr27.pdf\"]***************"  

My code looks like this:

image.rb

class Image < ActiveRecord::Base    dragonfly_accessor :image  end  

images_controller.rb:

def show    respond_to do |format|      format.html      format.pdf do        render pdf: 'name',               background: true,               encoding: 'utf8',               orientation: 'Landscape',               :show_as_html => params[:debug].present?      end    end  end  

show.pdf.erb:

<% if params[:debug].present? %>    <%= stylesheet_link_tag 'document' %>    <%= stylesheet_link_tag 'pdf' %>  <% else %>    <%= wicked_pdf_stylesheet_link_tag 'document' %>    <%= wicked_pdf_stylesheet_link_tag 'pdf' %>  <% end %>    ...    <%= image_tag image.url if image.image_stored? %>    ...  

image.url = http://localhost:3000/media/W1siZiIsIjYyIl1d/imagename.png

Any advice will be appreciated!

tokeninput not working in rails app

Posted: 07 Oct 2016 02:59 AM PDT

I have a rails application where I am trying to use jquery-tokeninput.

I have this in hotels.html.erb

<%= form_tag bookings_hotels_search_path, :method => 'get', :id => "searchForm" do %>    <div class="row-flex">      <div class="col-flex">        <div class="form-group relate">          <%= text_field_tag :destination, "", :placeholder => "Search Destination", :id => "destination" %>          <div class="dropdown-icon">            <i class="fa fa-pencil"></i>          </div>        </div>      </div>    </div>  <% end %>  

in same file at the end I have

<script type="text/javascript">  $(document).ready(function(){    $("#destination").tokenInput('/search_hotel_city.json',       { crossDomain: false,         zindex: 999,        tokenLimit: 1,        placeholder: "Search Destination",        propertyToSearch: 'city_name',        searchingText: "Searching ...",        hintText: "Search City Name",        tokenValue: "city_name",        minChars: 2,                resultsFormatter: function(item){ return "<li style='padding: 5px;border-top: 1px solid #C0C1C4;'><div style='display:inline-block; padding-left: 10px;padding-top:0px;vertical-align: middle;'><div class='full_name' style='color:#174862;font-size:13px;margin-top:0px;'>" + item.city_name + "</div></div><div class='clear'></div></li><div class='clear'></div>" },        preventDuplicates: true,        tokenFormatter: function(item) { return "<li><span id='dest_name'>" + item.city_name + "</span><span id='dest_id' class='hidden'>"+item.id+"</span></li>"},        onDelete: function(){          $('.token-input-input-token').show();        }    });  });  </script>  

In application.css.scss

*= require token_input  *= require token_input_facebook  *= require token-input-mac  

In application.js

//= require jquery-tokeninput  

When I type something in the destination field nothing happens. Need help.

Why does zeus do nothing randomly?

Posted: 07 Oct 2016 02:42 AM PDT

I frequently see Zeus do nothing in response to rake commands like so:

enter image description here

It also happens on migrations and pretty much any rake task I run. It's seemingly random. To work-around, I simply run the command multiple times until it works or it gives an output saying that it was already done.

Does anyone have this problem?

How login form works in ror?

Posted: 07 Oct 2016 05:28 AM PDT

I am trying to learn Ruby on Rails. I have followed youtube tutorial to create simple authentication in ruby. Everything is working fine but I cant understand it.

I have routes

resources :sessions, only: [:new, :create, :destroy]    get 'signup', to: 'users#new', as: 'signup'  get 'login', to: 'sessions#new', as: 'login'  get 'logout', to: 'sessions#destroy', as: 'logout'  

I have controllers for sessions and users

sessions_controller

def new  end    def create    user = User.find_by_email(params[:email])    if user && user.authenticate(params[:password])      session[:user_id] = user.id      redirect_to root_url, notice: 'Logged in !'    else      render :new    end  end    def destroy    session[:user_id] = nil    redirect_to root_url, notice: 'Logged out!'  end  

and my views/sessions/new.html.erb

<h1>Log In</h1>  <%= form_tag sessions_path do %>  <div class="field">  <%= label_tag :email %><br>  <%= text_field_tag :email %>  </div>   <div class="field">     <%= label_tag :password %><br>  <%= password_field_tag :password %>  </div>   <div class="actions">    <%= submit_tag "Log In" %>  </div>  <% end %>  

I want to understand how my login form works . I understand that when i go to /login it will request action from session controller and method new, but how it knows when i type my email and password and press submit what to do next ? In php there is . How it works in ruby ?

Dropzone doesnt load unless page is refreshed

Posted: 07 Oct 2016 02:41 AM PDT

I am using dropzone.js in a rails application. The dropzone is part of a form with other input elements. At page load the div containing the form is hidden. On the click of a button, that div slides down. However, at this stage Dropzone is not initialized. But it works absolutely fine if I refresh the page and click the same button again.

This is my dropzone function (inside document.ready)

function dropzoneControl() {      Dropzone.options.myDropzone = {          url: '/the_url',          autoProcessQueue: false,          uploadMultiple: true,          parallelUploads: 5,          maxFiles: 5,          maxFilesize: 3,          acceptedFiles: 'image/*',          addRemoveLinks: true,          headers: {              'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')          },          init: function() {              dzClosure = this;              document.getElementById("submit-button").addEventListener("click", function(e) {                  e.preventDefault();                  e.stopPropagation();                  dzClosure.processQueue();              });                //send all the form data along with the files:              this.on("sendingmultiple", function(data, xhr, formData) {                  formData.append("name", $("#name").val()); * * other data * *                });                //on successful upload              this.on("successmultiple", function(file, responseText) {                  $('#name').val(""); * * clear the rest of the form * *              });                this.on("queuecomplete", function(file) {                  this.removeAllFiles();              });          }      }  }  

How to use Execjs in Rails using Node.js

Posted: 07 Oct 2016 02:39 AM PDT

I'm trying to use Execjs but I need to run Node which is supported but I'm not sure of the syntax/setup process. The example from the docs is:

require "execjs"  require "open-uri"  source = open("http://coffeescript.org/extras/coffee-script.js").read    context = ExecJS.compile(source)  context.call("CoffeeScript.compile", "square = (x) -> x * x", bare: true)  # => "var square;\nsquare = function(x) {\n  return x * x;\n};"  

or

require "execjs"  ExecJS.eval "'red yellow blue'.split(' ')"  # => ["red", "yellow", "blue"]  

I'm trying to use JSON.stringify(string), this is my code below:

def method(string, password)    body = string.to_json    context = ExecJS.compile(body)    context.call("Node.compile", "JSON.stringify(context)", bare: true)    OpenSSL::HMAC.hexdigest(DIGEST_ALGORITHM, password, out_put_from_JSON_Stringify_goes_here )  end  

Currently I'm getting the error:

ExecJS::ProgramError: ReferenceError: node is not defined  from eval (eval at <anonymous> ((execjs):2:8), <anonymous>:1:2)  

I've added ENV['EXECJS_RUNTIME'] = 'Node' to config/boot.rb and tried variations of node, Node etc but still get the same errors.

Any help would be greatly appreciated,

Thanks

Ruby hashes group by multiple value

Posted: 07 Oct 2016 02:52 AM PDT

I have multiple hashes who looks like this:

[{"name" => "name1", "folder" => "folder1", id => 1 },    {"name" => "name1", "folder" => "folder1", id => 2 },    {"name" => "name1", "folder" => "folder2", id => 3},    {"name" => "name2", "folder" => "folder1", id => 4}]  

And my goal is to have something who looks like this:

   {"name1" =>       [{"folder1" =>        [{"name" => "name1", "folder" => "folder1", id => 1 },         {"name" => "name1", "folder" => "folder1", id => 2 }] }       {"folder2" =>          [{"name" => "name1", "folder" => "folder2", id => 3}] }]        {"name2" =>        [{"folder 1" =>          [{"name" => "name2", "folder" => "folder1", id => 4}] }] }  

I didn't find a proper solution who give exactly this kind or a similar result for now

1 comment:

  1. Life is good when you have your love ones around you, I am saying this because when i had issues with my lover i never seen life as a good thing but thanks to Dr. AGBAZARA of AGBAZARA TEMPLE, for helping me to cast a spell that brought my lover back to me within the space of 48hours. My husband left me for another woman after 7YEARS of marriage,but Dr.AGBAZARA help me cast a spell that brought him back to me within 48hours. I am not going to tell you more details about myself rather i will only advise those who are having issues in there relationship or marriages to contact Dr.AGBAZARA TEMPLE through these details via; ( agbazara@gmail.com ) or call him on Whatsapp: +2348104102662

    ReplyDelete