Tuesday, October 18, 2016

Order by count of a model's association with a particular attribute | Fixed issues

Order by count of a model's association with a particular attribute | Fixed issues


Order by count of a model's association with a particular attribute

Posted: 18 Oct 2016 07:59 AM PDT

Say I have the two models 'Users' and 'Appointments' where a user has_many appointments.

An appointment can be of two different types: typeA and typeB.

How can I write a query to order the users by the amount of typeB appointments they have?

I've looked into counter_cache but it seems to just count the number of the association (so in this case the number of appointments a user would have) and does not allow for the counting of a particular type of appointment.

Any help would be much appreciated!

jQuery: Adding appropriate structure to DOM (Rails 4)

Posted: 18 Oct 2016 07:20 AM PDT

I've got a notification Model of which I am listing all the notifications from a user.
Additionally I've got a notification partial which contains the structure of one single notification.

I now want to display that notification partial, when someone clicks on one listed notification.
Fortunately it is important that that notification gets displayed, the user clicked on previously.

My Code:
View (Haml)

                - if current_user.ordered_notifications.any?                      - if current_user.ordered_notifications.unread.exists?                          #notifications.amount                              = render 'notifications'                      - else                          #notifications                              = render 'notifications'                  - else                      #notifications                          %i.fa.fa-bell                          .dropdown-content.dd-notifications.left                              .box                                  .all                                      %p.smaller.bold.pointer.notifications-popup all notifications                    .notification-view  

_notification (haml)

= notification.title #what code is supposed to be here in order to display the correct notification?  

_notifications (haml)

- current_user.ordered_notifications.limit(3).each do |notification|      = link_to(update_notifications_user_path(id: notification.id), remote: true) do          = notification.title  

Controller

    def update_notifications        @notification = current_user.ordered_notifications.find(params[:id])        @notification.read = true        @notification.save!          respond_to do |format|          format.html { redirect_to @notification.link }          format.js # render users/update_notifications.js.erb        end      end  

jQuery

$('.notification-view').remove();  $('.notification-view').append("<%= j render 'notification' %>");  

Any help is appreciated! If you need additional information, please tell me.

Rails 4 - Simple Form - Jquery - How to add a class to an option in a selectbox

Posted: 18 Oct 2016 07:50 AM PDT

I am so confused - your help would be much appreciated. Could one kindly tell me how to add a class to a specific option in a select box.

As per the image, i would like to add a class only to the option: <option value="4">both X men & X women</option> but i am unsure how

_form.html.erb

<%= simple_form_for [@user, @social] do |f| %>    <%= f.error_notification %>      <div class="form-inputs">      <%= f.association :category_quantitygender, collection: CategoryQuantitygender.all, prompt: "select a category", label: "Quantity Gender Selection", input_html: { class: 'category_select' } %>    </div>      <div class="form-actions">      <%= f.button :submit %>    </div>  <% end %>  

i tried the below but no luck:

$(document).ready(function() {    $('#social_category_quantitygender_id').addClass($('here').val() == 4));  });  

enter image description here

Javasript does not work after j rendering a view

Posted: 18 Oct 2016 07:40 AM PDT

When I dynamically update content to a page using a remote call and a *js.erb file like this:

add_content.js.erb

$("#new_content").html('<%= j render("content") %>');  

To render a view like this: _content.html.erb

<div class="name">      <%= @content.name %>  </div>  <div class="text">      <%= @content.text %>  </div>  

With an javasript file like this: application.js

$( document ).ready(function() {      ...      $(".name").on('click', function(){        $(".text").slideToggle();      });      ...  })  

... the javascript slideToggle() is not executed. When I do

<%= render("content") %>   

in any view (without js.erb) everything works as expected and slideToggle() works. This is just a quick example to keep it simple, it is not related to slideToggle, even alert("...") etc. will not work.

So my question is why is javascript not executed? Is this related to any loading order? Do I need to re-initialize something?

Rails: Test case is failing when running all the test cases simultaneously in rubymine

Posted: 18 Oct 2016 07:14 AM PDT

I am running test case with rubymine. whenever i run individual test case it works and But one of my test case is failed whenever i run all the test cases simultaneously.

Below is the error that i am getting.

Fail to load: D:/image-resource-planning/test/models/fact_revenue_cost_test.rb:1        Exception message: superclass mismatch for class FactRevenueCostTest  ["D:/image-resource-planning/test/models/fact_revenue_cost_test.rb:4:in `(root)'", "org/jruby/RubyKernel.java:1065:in `require'", "C:/jruby-1.7.16/lib/ruby/gems/shared/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:274:in `require'", "C:/jruby-1.7.16/lib/ruby/gems/shared/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:in `load_dependency'", "C:/jruby-1.7.16/lib/ruby/gems/shared/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:274:in `require'", "C:/Program Files (x86)/JetBrains/RubyMine 2016.2.4/rb/testing/runner/tunit_or_minitest_in_folder_runner.rb:1:in `(root)'", "org/jruby/RubyArray.java:1613:in `each'", "C:/Program Files (x86)/JetBrains/RubyMine 2016.2.4/rb/testing/runner/tunit_or_minitest_in_folder_runner.rb:51:in `require_all_test_scripts'", "C:/Program Files (x86)/JetBrains/RubyMine 2016.2.4/rb/testing/runner/tunit_or_minitest_in_folder_runner.rb:44:in `require_all_test_scripts'", "org/jruby/RubyKernel.java:1081:in `load'", "-e:1:in `(root)'"]  

How to download each zip file from a url and unpack using rails

Posted: 18 Oct 2016 07:40 AM PDT

Right now I have a URL which is populated with a list of .zip files in the browser. I am trying to use rails to download the files and then open them using Zip::File from the rubyzip gem. Currently I am doing this using the typhoeus gem:

response = Typhoeus.get("http://url_with_zip_files.com")  

But the response.response_body is an HTML doc inside a string. I am new to programming so a hint in the right direction using best practices would help a lot.

response.response_body => "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n<html>\n <head>\n  <title>Index of /mainstream/posts</title>\n </head>\n <body>\n<h1>Index of /mainstream/posts</h1>\n<table><tr><th><a href=\"?C=N;O=D\">Name</a></th><th><a href=\"?C=M;O=A\">Last modified</a></th><th><a href=\"?C=S;O=A\">Size</a></th><th><a href=\"?C=D;O=A\">Description</a></th></tr><tr><th colspan=\"4\"><hr></th></tr>\n<tr><td><a href=\"/5Rh5AMTrc4Pv/mainstream/\">Parent Directory</a></td><td>&nbsp;</td><td align=\"right\">  - </td><td>&nbsp;</td></tr>\n<tr><td><a href=\"1476536091739.zip\">1476536091739.zip</a></td><td align=\"right\">15-Oct-2016 16:01  </td><td align=\"right\"> 10M</td><td>&nbsp;</td></tr>\n<tr><td><a href=\"1476536487496.zip\">1476536487496.zip</a></td><td align=\"right\">15-Oct-2016 16:04  </td><td align=\"right\"> 10M</td><td>&nbsp;</td></tr>"  

LoadError: incompatible library version - /usr/local/rvm/gems/ruby-2.2.1/gems/nokogiri-1.6.8.1/lib/nokogiri/nokogiri.so

Posted: 18 Oct 2016 06:51 AM PDT

When I try to run rake db:migrate it's showing below error -

LoadError: incompatible library version - /usr/local/rvm/gems/ruby-2.2.1/gems/nokogiri-1.6.8.1/lib/nokogiri/nokogiri.so /usr/local/rvm/gems/ruby-2.2.1/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:32:in require' /usr/local/rvm/gems/ruby-2.2.1/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:32:in rescue in ' /usr/local/rvm/gems/ruby-2.2.1/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:28:in <top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/loofah-2.0.3/lib/loofah.rb:3:in require' /usr/local/rvm/gems/ruby-2.2.1/gems/loofah-2.0.3/lib/loofah.rb:3:in <top (required)>' /mnt/vinod/MLO_CODE/config/application.rb:5:in ' /mnt/vinod/MLO_CODE/Rakefile:5:in <top (required)>' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-11.3.0/exe/rake:27:in' LoadError: cannot load such file -- nokogiri/2.3/nokogiri /usr/local/rvm/gems/ruby-2.2.1/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:30:in require' /usr/local/rvm/gems/ruby-2.2.1/gems/nokogiri-1.6.8.1/lib/nokogiri.rb:30:in ' /usr/local/rvm/gems/ruby-2.2.1/gems/loofah-2.0.3/lib/loofah.rb:3:in require' /usr/local/rvm/gems/ruby-2.2.1/gems/loofah-2.0.3/lib/loofah.rb:3:in ' /mnt/vinod/MLO_CODE/config/application.rb:5:in <top (required)>' /mnt/vinod/MLO_CODE/Rakefile:5:in' /usr/local/rvm/gems/ruby-2.2.1/gems/rake-11.3.0/exe/rake:27:in `' (See full trace by running task with --trace)

Can Anybody assist me on this ?

Rails Controller: How to return list of specific objects?

Posted: 18 Oct 2016 06:54 AM PDT

I want to set my @users variable to a specific list of users (whose id's are specified in a file).

This is my controller:

class UsersController < ApplicationController  unloadable  require 'will_paginate/array'    ENTRIES_PER_PAGE = 15    def index      if some_condition        @users = User.all      ...      ...      ...        /* inside else block */      ids = []      File.open("./user_ids.txt", "r") do |f|        f.each_line do |line|          ids.push[line]        end      end        /* ??? */  #   @users = User.find(ids)      /* When above line is uncommented, application throws error */  

The commented line throws an error, I think because @users isn't an array, but something else, and I'm not sure what I'm supposed to do.

ActionView::Template::Error (undefined method `total_entries' for #<Array:0x000000044aa688>)  

total_entries is defined from the will_paginate gem

<p> Total entries: <%= @users.total_entries %> </p>  

Rails nested form fields_for doubled in edit

Posted: 18 Oct 2016 06:37 AM PDT

I'm trying to create a form where users can see a list of their friends and add or remove friends from lists (sort of like facebook's groups). For the create list view, I can get the form working properly, but for the edit view I'm having trouble with check_box syntax and fields_for.

routes.rb    resources :friendships    resources :friend_lists    class User < ActiveRecord::Base  has_many :friendships, dependent: :destroy    has_many :friends, through: :friendships    has_many :friend_lists    has_many :flist_memberships, class_name: 'FlistMembership', foreign_key: 'member_id', dependent: :destroy  ...  end    class FriendList < ActiveRecord::Base    belongs_to :user    has_many :flist_memberships    has_many :members, through: :flist_memberships      accepts_nested_attributes_for :members, allow_destroy: true    accepts_nested_attributes_for :flist_memberships, allow_destroy: true  end    class FlistMembership < ActiveRecord::Base    belongs_to :friend_list    belongs_to :member, class_name: 'User'  end    class FriendListsController < ApplicationController    def new      @friend_list = current_user.friend_lists.build      @friends = current_user.friends.paginate(page: params[:page])      @friend_list.flist_memberships.build    end      def create      @friend_list = current_user.friend_lists.build(friend_list_params)      respond_to do |format|          format.html {            if @friend_list.save              flash[:success] = "Friends list created!"              redirect_to friendships_path            else              render 'friend_lists/new'            end            }        end    end      def edit      @friend_list = FriendList.find(params[:id])      @friends = current_user.friends    end      def update      @friend_list = FriendList.find(params[:id])      if @friend_list.update_attributes(friend_list_params)        flash[:success] = "Friend list updated!"        redirect_to friend_list_path(@friend_list)      else        render 'edit'      end    end      private      def friend_list_params      params.require(:friend_list).permit(:name, flist_memberships_attributes: [:id, :member_id, :friend_list_id])    end  end  

new.html.erb

<%= form_for @friend_list do |f| %>    <%= f.label :name, "Name for this friends list:" %>    <%= f.text_field :name %>    <% @friends.each do |friend| %>      <%= f.fields_for :flist_memberships do |m| %>        <%= m.check_box :member_id, {}, friend.id %>        <%= m.label :member_id, friend.name %>      <% end %>    <% end %>    <%= f.submit "Save", class: "btn btn-primary" %>  <% end %>  

edit.html.erb

<%= form_for @friend_list do |f| %>    <%= f.label :name, "Name for this friends list:" %>    <%= f.text_field :name %>    <%= f.fields_for :flist_memberships do |m| %>      <%= m.collection_check_boxes(:member_id, @friends.all, :id, :name) %>    <% end %>    <%= f.submit "Save", class: "btn btn-primary" %>  <% end %>  

new.html.erb renders and saves the selected items correctly, but I can't figure out how to write the edit form so that it doesn't iterate through the collection once for each item in the collection (both with collection_check_boxes and the form as written in new.html.erb). Trying

<%= f.fields_for :flist_memberships do |m| %>    <%= m.check_box :id %>    <%= m.label :id, :name %>  <% end %>  

in the edit form just passes the string "id" as params rather than pulling the id of each member in the collection, and I'm not sure how to pull the individual item's name/id without iterating over the collection, which goes back to the multiple renders problem. I'm using cocoon elsewhere in the project, but for this I'd rather present the user a list of all options and allow them to check a box for each one, rather than having to manually add each item on the list. If there is a way to do it with cocoon, I'd be happy to hear it.

NoMethodError: undefined method `merge!' for "branch_name":String

Posted: 18 Oct 2016 06:03 AM PDT

I using a gem TinyBucket for retriving commit messages from BitBucket:

When I was trying to retrieve commit messages from a particular branch by looping all the commits of the branch as mentioned in the documentation.

Documentation:

repo = bucket.repo('someone', 'great_repo')    # [x] GET a commits list for a repository or compare commits across branches  # branchortag, include, exclude options  commits = repo.commits(options)  

My code:

commits = repo.commits('branch_name')   #<Tinybucket::Resource::Commits:0x00000005faca30 @repo=#<Tinybucket::Model::Repository:0x00000007afef68 @_loaded=false, @repo_owner="owner_name", @repo_slug="sample_app">, @args=["static-pages-exercises"]>     commits.each do |commit|      puts commit.message  end  

Error message after that loop:

NoMethodError: undefined method `merge!' for "branch_name":String      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/iterator.rb:73:in `next_params'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/iterator.rb:58:in `load_next'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/iterator.rb:44:in `next_value'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/iterator.rb:23:in `next'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/enumerator.rb:17:in `block (2 levels) in initialize'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/enumerator.rb:16:in `loop'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/enumerator.rb:16:in `block in initialize'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/resource/base.rb:12:in `each'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/resource/base.rb:12:in `each'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/tinybucket-1.2.0/lib/tinybucket/resource/base.rb:12:in `method_missing'      from (irb):357      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/console.rb:65:in `start'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in `start'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'      from /home/atchyut/.rvm/gems/ruby-2.3.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'      from bin/rails:4:in `require'      from bin/rails:4:in `<main>'2.3.0 :360 >   

Can someone please explain how should I have to send branch name for the options argument to retrieve individual commit messages?

Ruby on Rails gem install bundler

Posted: 18 Oct 2016 05:48 AM PDT

Please help gem install bundler, here is why: Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed.

Here's the error (Git Bash/Windows 8.1 64-Bit):

$ ruby --version  ruby 2.2.4p230 (2015-12-16 revision 53155) [i386-mingw32]      $ gem --version  2.4.5.1      $ rake --version  rake, version 10.4.2      $ rails --version  Rails 4.2.5.1      $ gem install bundler  ERROR:  Could not find a valid gem 'bundler' (>= 0), here is why:            Unable to download data from https://rubygems.org/ - SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://api.rubygems.org/specs.4.8.gz)  

Thanks

Can we extract information from resume means .pdf file or word file and excel file in rails

Posted: 18 Oct 2016 06:22 AM PDT

I have a resume and I want to upload or drag and drop from my local system, at that time I want to extract some information from resume ( .pdf file, word file, excel file) like name, email, contact number, etc.

It is possible to extract information from file, then automatic signup.

Please post answer properly, I have tried so many times..

Create rails routes only for localhost

Posted: 18 Oct 2016 06:42 AM PDT

I'd like certain rails routes to only be accessible from localhost. In other words if you attempted to access that url from a non localhost connection you would be given a response equivalent to the route not existing.

Optimally some way of specifying routes as local in the routes.rb itself would be the cleanest solution but if there is some way to filter the request later at the controller level for example thats okay too.

Same session is used in rails 2.3.2 App before and after login to the App

Posted: 18 Oct 2016 05:00 AM PDT

We build a rails 2.3.2 app and has login/logout mechanism using rails session/cookies to log in (not using device gem).

After log out, we are resetting the session by using rails reset_session which will drop the session data and create a new session. Created session will be available in a browser (cookies[_session_id]) and after successful login (username-password), the same session is used in the application.

Question

  1. Why is session same before and after login?

  2. How to create a new session after a successful login?

I don't want to build this by using device gem or any other gem.

Attached screenshot, please check and give me solutions.

enter image description here

enter image description here

How do I DRY-ly handle multiple upload types with Carrierwave?

Posted: 18 Oct 2016 05:26 AM PDT

I want to allow my users to be able to upload videos, documents & images to s3.

I was thinking that rather than having a model for each and then having 3 different uploader classes, I would just have 1 generic uploader and just whitelist all of those filetypes.

But I am not sure if that's the best approach, from a security perspective?

Also, there may be small variations with each type. For instance, with video a user should be able to both upload a video, or alternatively provide a YouTube link.

What's the most Rails/DRY-way to approach this?

How to order table with title including numbers?

Posted: 18 Oct 2016 05:35 AM PDT

Titles in my table looks like that:

"Title 100"  "Title 17"  "Title 2"  "Title 23"  

And I want to order them like below:

"Title 2"  "Title 17"  "Title 23"  "Title 100"  

When I use Post.order("title ASC").each { |post| puts post.title } I got below results:

"Title 100"  "Title 17"  "Title 2"  "Title 23"  

How to solve this issue?

Structure rails association[user -> one review -> single model]

Posted: 18 Oct 2016 05:16 AM PDT

I have 3 models user, app and review

Current my models have the following associations

User -> has_many :reviews, has_many :apps

Review -> belongs_to :app, belongs_to :user

App -> has_many :reviews, belong_to :user

This allow user to create multiple reviews on a simple app model

My question: How to structure my models so that user can add only one review in a single app model? How to ensure that user can not add review to app he/she created?

Railsapp Fails To Bind -b 0.0.0.0

Posted: 18 Oct 2016 04:41 AM PDT

rails s -b /usr/lib/ruby/vendor_ruby/thor/base.rb:483:in handle_argument_error': ERROR: "rails server" was called with arguments ["-b"] (Thor::InvocationError) Usage: "bin/rails server [options]" from /usr/lib/ruby/vendor_ruby/thor/command.rb:34:inrescue in run' from /usr/lib/ruby/vendor_ruby/thor/command.rb:21:in run' from /usr/lib/ruby/vendor_ruby/thor/invocation.rb:126:ininvoke_command' from /usr/lib/ruby/vendor_ruby/thor.rb:359:in dispatch' from /var/lib/gems/2.3.0/bundler/gems/rails-454460e87ea9/railties/lib/rails/command/base.rb:61:inperform' from /var/lib/gems/2.3.0/bundler/gems/rails-454460e87ea9/railties/lib/rails/command.rb:34:in invoke' from /var/lib/gems/2.3.0/bundler/gems/rails-454460e87ea9/railties/lib/rails/commands.rb:16:in' from script/rails:18:in require' from script/rails:18:in'

Rails 4, SQ Lite 3: Access model through model without an association

Posted: 18 Oct 2016 06:26 AM PDT

I've got two tables:

item
recipe

In this example I've got an item object item with the id 1. The item table has one column named recipe_id. For this object it has the value 2.

recipe has a column named title.

How can I get for example the title from the recipe of which the id is linked in item, if I have the item?

Something like...?

= item.recipe_id.title  

Thanks in advance for any help!

Strange slow page loading or something similar. Bootstrap

Posted: 18 Oct 2016 04:18 AM PDT

so I just pushed my page to heroku: https://stark-dawn-83245.herokuapp.com/

and if I open it, click on photo, try to log in or do some kind of stuff - pages load with strange flashy style. You can see it yourself. This is not happening on my local host.

Can someone please explain to me what is happening? Or at least point me to some documentation about this kind of stuff.

Rails Composite Keys - Setting up models and assocs

Posted: 18 Oct 2016 05:05 AM PDT

I'm using Rails Composite Keys for the first time and even though I've read the docs, I'm still unsure how to set up the models correctly.

An Activity can be Scheduled by a Provider. I want a join table that tracks activity_id and provider_id as a unique composite key so that I can associate it with something else (prices). The composite needs to be generated upon the creation of a new schedule. The provider does not necessarily own the activity themselves directly.

I've got this for my composite key as it's own model. Is this right?

class ScheduledActivity < ActiveRecord::Base    self.primary_keys = :provider_id, :activity_id    belongs_to :activity    belongs_to :provider    has_many :schedules, :foreign_key => [:provider_id, :activity_id]    has_many :prices, :foreign_key => [:provider_id, :activity_id]  end  

This for the db migration:

class CreateJoinTableScheduledActivities < ActiveRecord::Migration    def change      create_join_table :providers, :activities, table_name: :scheduled_activities do |t|        t.index [:provider_id, :activity_id]      end    end  end  

How do I then get new entries on the join table as Schedules are created? Do I put only belongs_to :scheduled_activity on this model - i.e. no provider and activity ids on the Schedule table, and do I write a separate hook in order to create the new composite keys?

(Also - is this the correct use case for composite keys in the first place?!)

Thanks in advance!

LoadError: cannot load such file -- active_resource

Posted: 18 Oct 2016 06:10 AM PDT

I have two applications named as 'Book' and 'Inventory' respectively. My 'Book' app is running on 3000 port & 'Inventory' app is running on 4000 port. I have 'book' model in 'Book' app and 'inventory' model in 'Inventory' app. In my 'Book' app I have created inventory.rb file inside app/models folder as below

require 'active_resource'    class Inventory < ActiveResource::Base    self.site = 'http://localhost:4000'  end  

In gemfile I have included :

gem 'activeresource'  

When I am trying to access Inventory model from my 'Book' app console, I am getting below error

2.0.0-p643 :234 >   require 'active_resource'  LoadError: cannot load such file -- active_resource  

Or when I am trying

Invetory.last  

I am getting the same error.

Sidekiq logs show job ID instead of job name

Posted: 18 Oct 2016 07:30 AM PDT

I have a Rails application that runs some background jobs via ActiveJob and Sidekiq. The sidekiq logs in both the terminal and the log file show the following:

2016-10-18T06:17:01.911Z 3252 TID-oukzs4q3k ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper JID-97318b38b1391672d21feb93 INFO: start  

Is there some way to show the class names of the jobs here similar to how logs work for a regular Sidekiq Worker?

Update:

Here is how a Sidekiq worker logs:

2016-10-18T11:05:39.690Z 13678 TID-or4o9w2o4 ClientJob JID-b3c71c9c63fe0c6d29fd2f21 INFO: start  

Getting multiple buttons for the same action

Posted: 18 Oct 2016 05:43 AM PDT

I have a blog rails app where users can comment on an article and the article author can message the user directly from the comment for which i have added a send message button, i am using mailbox for getting the message option, everything is working but the problem is when there are multiple comments the message button also get multiplied, but i don't want that what i am trying to have is one message button for each comment.

This is what am getting right now: this is the problem

my code

    <div id="comments">    <h2 class="comment_count">      <%= pluralize(@shipment.comments.count, "Bid") %>    </h2>    <% @comments.each do |comment| %>      <div class="comment">          <li class="round-image-50"><%= image_tag(current_user.avatar.url(:thumb)) %></li><h6 class="username"><strong><font style="text-transform: capitalize;"><%= comment.user.full_name %></strong></font></h6>        <div class="shipment">        <p class="content">          <div class="text-center left col-md-4">        <%= comment.content %>      </div>        <% if @shipment.user == current_user %>        <% @shipment.comments.each do |comment| %>        <%= link_to 'Send Message', new_conversation_path(recipient_id: comment.user_id), class: "btn btn-default btn-xs" %>        <% end %>        <% end %>      </p>      </div>    </div>        <% end %>    <%= render "comments/form" %>   </div>  

if/else in controller and view Rails

Posted: 18 Oct 2016 04:47 AM PDT

I have an app that I am integrating Bitcoin into using BlockIo API. When a user wants to make a payment, a new Bitcoin address is created for them and saved on the db, and after they make a payment the the amount is also saved, and that amount is retrieved from the API. I need assistance with the syntax or proper way to get the conditional statement working.

To generate and save a new Bitcoin address in the controller the code is:

@new_address = BlockIo.get_new_address  Payment.create( btc: @new_address['data']['address'] )  

I want to create a conditional statement that will display the already generated bitcoin address if the amount (amount:) of the last Payment (Payment.last) is <= '0.00000000' || == nil, else generate a new address.

The attributes for the Payment model/controller are bitcoin:string and amount:string

What I have thus far is:

def create_address    @last_address = Payment.last.bitcoin    @last_amount = Payment.last.amount      if @last_amount == '0.00000000' || @last_amount == nil      @last_address    else      @new_address = BlockIo.get_new_address      Payment.create( btc: @new_address['data']['address'] )    end  end  

But the above code is not working, as it does not generate a new address when I update last Payments' amount to a bigger amount via console.

And I am also not sure how to display these results in the view, as I have the following:

Send your Bitcoins to:

<% if @last_address %>    <strong><%= @last_address %></strong><br>    <%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=#{@last_address}" %>  <% else %>    <strong><%= @new_address['data']['address'] %></strong><br>    <%= image_tag src="https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=#{@new_address["data"]["address"]}" %>  <% end %>  

I have checked the Rails guides and have come thus far, any comments or assistance will be greatly appreciated, I need assistance with syntax and making the above conditions to work.

How can I do something like this with ruby arrays

Posted: 18 Oct 2016 04:44 AM PDT

I have an user array like this:

users_array = [[1,text for 1],[2,text for 2],[3,text for 3],[4,text for 4],[5,text for 5]]  

here first element is user_id and second element is text which is specific to user_id in the same array.

Now I am trying to have user object from instead of ids in array like these.

users_array = [[#<User id: 1, encrypted_email: "">,text for 1],[#<User id: 2, encrypted_email: "">,text for 2],[#<User id: 3, encrypted_email: "">,text for 3],[#<User id: 4, encrypted_email: "">,text for 4],[#<User id: 5, encrypted_email: "">,text for 5]]  

I am trying not to loop the array and hit the db thousand times for thousands user.

Ruby on Rails - Add limit, order and sum on File.open

Posted: 18 Oct 2016 04:03 AM PDT

In my application I have a .txt file that I open/read on users profile view. That .txt file contains some numbers.

This is what i have so far:

f = File.open("public/users/14/user.txt", "r")  - f.each_line do |d|       %p= d  

I can put out all the numbers that is on that file. Is it any way to add limit & order (start from bottom to top).

I tried:

f.limit(4).order('DESC').each_line do |d|  

and

File.open("public/users/14/user.txt", "r").limit(5)  

When I try these I get error: undefined method limit or undefined method order.

Is it also possible to sum all the numbers on that file?

Paperclip and pure attachment model

Posted: 18 Oct 2016 06:07 AM PDT

In my Rails application I want to have a simple file storage. This leads me to creating an Attachment model (File is already used in Ruby).

I'm using Paperclip so I finished with this:

class Attachment < ApplicationRecord    has_attached_file :attachment, styles: { thumb: '150x150>' }    validates :attachment, attachment_presence: true  end  

and this:

create_table "attachments", force: :cascade do |t|    t.string   "name"       t.datetime "created_at",              null: false    t.datetime "updated_at",              null: false    t.string   "attachment_file_name"    t.string   "attachment_content_type"    t.integer  "attachment_file_size"    t.datetime "attachment_updated_at"  end  

Because of that, I need to write not nice things like

params.require(:attachment).permit(:attachment)  

or

some_file.attachment  

Is there a better way to do this or is my way good enough?

Google::Apis::AuthorizationError: Unauthorized

Posted: 18 Oct 2016 03:34 AM PDT

Recently i have errors authenticating subsequent requests to Google Calendar API.

  def google_auth(access_token)      client = Signet::OAuth2::Client.new(access_token: access_token)    end    def auth_with_oauth2_service(access_token)      auth_client = google_auth(access_token)      service = Google::Apis::Oauth2V2::Oauth2Service.new      service.client_options.application_name = "emma-calendar-auth"        service.authorization = auth_client        return service    end  

this is the code i had so far and it worked. But not it stopped and it throws an "unauthorized" message.

I am using latest google-api-client gem.

I have tried these solutions below

creating a class of

class AccessToken      attr_reader :token      def initialize(token)        @token = token      end        def apply!(headers)        headers['Authorization'] = "Bearer #{@token}"      end    end  

the above solution solved another error "Missing token endpoint URI" but it does not work for Google::Apis::CalendarV3::CalendarService.new -> only with Google::Apis::Oauth2V2::Oauth2Service.new

Next i tried this

authorization = Signet::OAuth2::Client.new(access_token: access_token)    # Signet 0.7.3 raises when the expiration date is nil,  # so we set an arbitrary date in the future  authorization.expires_in = Time.now + 1_000_000  

which again is not working. Any help is welcomed!

Is it possible to use JS code with in ruby code?

Posted: 18 Oct 2016 03:40 AM PDT

I am created Rail application with erb views. I want to use some JS code with in ruby code like following

<script>     $('#select-service').click(function() {         var service='<%= Service.find("this.id") %>';      });  </script>  

I want to query based on user selected value. How to replace "this.id" used above and how to insert js code instead of "this.id" ?

No comments:

Post a Comment