Saturday, April 16, 2016

Rails controller querying by date comparison | Fixed issues

Rails controller querying by date comparison | Fixed issues


Rails controller querying by date comparison

Posted: 16 Apr 2016 07:15 AM PDT

I am using model's scope to make filter for my queries.

Something like this where I am filtering all x workers belonging to a company_id

scope :company_id, -> (company_id) { where company_id: company_id }  

But now I am making a more complex query. Let's say for example I have the model Worker and I want to query the workers assigned to a company_id from the latest 5 days.

So in my models I created this filter scope:

scope :latest, -> (created_at) { where created_at: >= Time.now - 5.day}    @company = Company.find(params[:id])  @workers = Worker.company_id(@company.id).latest(??)  

Rails asset loaded too late

Posted: 16 Apr 2016 07:08 AM PDT

I have a rails view like this:

<%= javascript_include_tag "my_js" %> <%# foo function is defined here %>    <div>    <%# stuff %>  </div>    <script>    $(document).ready(function() {        foo();    });  </script>  

And when I load this page, I have this error:

Uncaught ReferenceError: foo is not defined  

However, when I refresh the page, everything works fine.

What I find really strange is that, even if I access the page multiple times using only the links on my site, the error will pop every time. I really have to use a refresh for the script to load!

What could be the cause of this?

Safari address bar shows a blank page with "data:," after posting a form

Posted: 16 Apr 2016 07:06 AM PDT

When I post a form to my rails website (using turbolinks, not sure if it is relevant) from safari on mac, instead of redirecting to the next page, it just shows a blank page, with "data:," in the address bar.

I have an embedded youtube video on the page, in case that is relevant. Also, my form has a textarea that uses ckeditor.

The record is saved, just that it does not redirect to the show page as I would expect.

This does not happen on chrome.

The page source for the blank page shows up as:

<html> = $0<head></head><body></body></html>  

Rails 4 cache class and instance

Posted: 16 Apr 2016 07:10 AM PDT

I use ActiveAdmin and I want to implement some caching. For example, I want to cache filters part, which contains resource class and resource field symbol. The simplest error example is here:

    [1] pry(#<ActiveAdmin::ResourceDSL>)> Rails.cache.fetch [City, 'fff']      SystemStackError: stack level too deep      from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/core_ext/object/json.rb:159:in `dup'    or if I run in clear pry, it will crush with:    [37] pry(main)> Rails.cache.fetch [City, 'fff']  /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/last_exception.rb:54:in `bt_source_location_for': undefined method `[]' for nil:NilClass (NoMethodError)                                                                                     from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/last_exception.rb:15:in `initialize'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:494:in `new'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:494:in `last_exception='          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:331:in `rescue in handle_line'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:317:in `handle_line'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:243:in `block (2 levels) in eval'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:242:in `catch'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:242:in `block in eval'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:241:in `catch'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_instance.rb:241:in `eval'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/repl.rb:77:in `block in repl'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/repl.rb:67:in `loop'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/repl.rb:67:in `repl'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/repl.rb:38:in `block in start'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/input_lock.rb:61:in `__with_ownership'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/input_lock.rb:79:in `with_ownership'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/repl.rb:38:in `start'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/repl.rb:15:in `start'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-0.10.3/lib/pry/pry_class.rb:169:in `start'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/pry-byebug-3.3.0/lib/pry-byebug/pry_ext.rb:11:in `start_with_pry_byebug'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in `start'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in `start'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in `console'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require'          from /home/kvokka/proj/bilet18/bin/rails:9:in `<top (required)>'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `block in load'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'          from /home/kvokka/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'          from -e:1:in `<main>'  

Where I'm wrong and how I can pass class in cache? (or I must to_s it before? why?)

UPDATE

I look throw class object, and saw, that it does not :cache_key method. I think it may be the cause

invite facebook friends to application and keep track whether they accepted

Posted: 16 Apr 2016 06:20 AM PDT

Lets say Jeff is registered to my Rails application and would like to invite Facebook friend John. Till this part is ok.

But then if John accepts the app invitation request, Jeff will earn 5 points. To do that i should be checking somehow if John accepts and invited by Jeff.

How do I do that? Thank you

CoffeeScript in Rails toggle div based on Collection Select

Posted: 16 Apr 2016 07:13 AM PDT

I have a Rails app using a somewhat basic form and I need some help with some coffeescript. Here is an excerpt of my form code:

  <%= f.label :Patient_Insurance, "Patient Insurance", class: "control-label" %>    <%= f.collection_select(:insurance_id, Insurance.order("insurance_type ASC"), :id, :insurance_type, {:include_blank => true}, {:class => 'select'}) %></br>    <div id="medicaid_fax_number">        <%= f.label :medicaid_fax_number %>        <%= f.text_field :medicaid_fax_number, placeholder: '2812224444' %>    </div>  

What I want to happen is to keep the medicaid_fax_number field always hidden unless a user chooses "Medicaid" from the collection_select, then display the div.

I am really rusty on JS and Coffee script so I could really use a hand with this one. I know that the thing I'm watching to change is the call_insurance_id (which is the ID in the form for the insurance collection select). But I'm not sure in coffeescript how to evaluate whether or not the value is equal to "Medicaid".

I'll continue to do some more research and keep working at it, but I figured someone here more knowledgeable than I could help.

RSpec with Devise: subject.current_user is nil when used in second method in a context

Posted: 16 Apr 2016 07:09 AM PDT

I am currently using RSpec to test my Rails 4 application and when testing, I found this strange problem: subject.current_user is nil in the second method in a context. Code snippet:

  describe 'GET #register_as_team:' do      context 'user logged in but not admin:' do        login_user        it 'should redirect_to user_path if user is not student' do          get :register_as_team, id: subject.current_user.id          expect(response).to redirect_to(user_path(subject.current_user))          expect(flash[:danger]).not_to be_nil        end          it 'should redirect_to student_path if user is a non-pending student' do          student = FactoryGirl.create(:student, user: subject.current_user, is_pending: false)          get :register_as_team, id: subject.current_user.id          expect(response).to redirect_to(student_path(student))        end      end    end  

So when subject.current_user is used first time, it is OK and I can just get the logged user but in the second method it returns nil.

For background information, login_user is like this:

module ControllerMacros    def login_user(user = nil)      before(:each) do        # @request.env["devise.mapping"] = Devise.mappings[:user]        user ||= User.find_by(email: 'default_user@controller.spec')        user ||= FactoryGirl.create(:user, email: 'default_user@controller.spec', uid: 'default_user.controller.spec')        sign_in user      end    end  end  

How to add multiple sub domains for a single app in heroku?

Posted: 16 Apr 2016 07:05 AM PDT

I am working on a Ruby On Rails app, it has multiple sub-domains for example: "admin.example.com", "user.example.com", "members.example.com" , so my question is how to deploy my app so that all these sub-domains work in staging mode in heroku. It is working fine on local host (using lvh.me to access subdomains). Right now I am not using any custom domain , I am using default domain name provided by Heroku.

Rails 4 Javascript files not working

Posted: 16 Apr 2016 05:42 AM PDT

Hello i have some problem with including javascript files to my rails app.

I'm using rails 4

first i write to these files names to my application.js

//= require jquery  //= require jquery_ujs  //= require turbolinks  //= require CanvasRenderer  //= require Projector  //= require three.min  //= require me  //= require_tree .  

they are have on my vendor/assets/javascripts too. So when i open my page from browser nothing working

i look to page source and can see that, my js files getting from header

  <link rel="stylesheet" media="all" href="/assets/home.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="true" />  <link rel="stylesheet" media="all" href="/assets/application.self-e80e8f2318043e8af94dddc2adad5a4f09739a8ebb323b3ab31cd71d45fd9113.css?body=1" data-turbolinks-track="true" />    <script src="/assets/jquery.self-660adc51e0224b731d29f575a6f1ec167ba08ad06ed5deca4f1e8654c135bf4c.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/jquery_ujs.self-e87806d0cf4489aeb1bb7288016024e8de67fd18db693fe026fe3907581e53cd.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/turbolinks.self-c37727e9bd6b2735da5c311aa83fead54ed0be6cc8bd9a65309e9c5abe2cbfff.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/CanvasRenderer.self-28076336bdf42eb56ef55649b880be9c4c40f4f9991aaa7cae7ba317c60e57a6.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/Projector.self-b4b1414a2f0bcaf573fcbc6a52ee0a989659089fe0d392f13545f1f065e1abd9.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/three.min.self-9bfe8e307ba0fd9ffeb655fcfc20d5017f34a3d41235b34e06b5fac3da6fd8f1.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/me.self-673e4489da4471935b3097fdd8e29ab07f0bc14dc377bca6dc9cd9cf6e39ec23.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/home.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="true"></script>  <script src="/assets/application.self-10ad0916cf31256fe71785e8dc9cc297a96b1cdf7b74aeb61711199b9a3d003f.js?body=1" data-turbolinks-track="true"></script>    <meta name="csrf-param" content="authenticity_token" />  <meta name="csrf-token" content="bs8wy2VKuszAk+pdH1e8cLLsL+P21x0Xm8hY76MoccKCPYiKE+QpGqHHuoWe7lwpvOgVsRW/3pyzf6OqBO23YA==" />    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">  </head>  

and console log give an error

CanvasRenderer.self-28076336bdf42eb56ef55649b880be9c4c40f4f9991aaa7cae7ba317c60e57a6.js:6 Uncaught ReferenceError: THREE is not defined  Projector.self-b4b1414a2f0bcaf573fcbc6a52ee0a989659089fe0d392f13545f1f065e1abd9.js:8 Uncaught ReferenceError: THREE is not defined  me.self-673e448….js?body=1:22 Uncaught TypeError: Cannot read property 'appendChild' of null  

the same files i'm using here and everything is okey. http://kleaz.com/demo/dev/

i can't understand why

can't upload file ruby on rails

Posted: 16 Apr 2016 05:23 AM PDT

i'm working with ruby on rails, and i want to upload a file using gem 'carrierwave', i don't have error buh i dont see it in database it's empty all times, that's what i'm doing :

new.html.erb

<div class="field">   <%= f.label :cv, "Charger votre CV au format pdf" %><br />   <%= f.file_field :cv %>  

show.html.erb:

  <strong> cv :</strong> <%= link_to "cv", @user.cv.url %>  

controller:

def create  @user = User.new(params[:user])   if @user.save    flash[:success] = "Bienvenue dans mon application ruby on Rails!"    redirect_to @user  else    @titre = "Inscription"    render 'new'  end  

model:

attr_accessible :nom,  :cv      mount_uploader :cv, CvUploader  

i had add a db migrate but nothing change

"sorry for my bad english"

rspec model testing; method doesn't work

Posted: 16 Apr 2016 06:52 AM PDT

The method itself works as expected, but when I try to test it in the model spec the create part fails. The find part works well. What did I miss?

conversation.rb

scope :between, -> (sender_id, recipient_id) do    where("(conversations.sender_id = ? AND conversations.recipient_id = ?) OR (conversations.sender_id = ? AND conversations.recipient_id = ?)", sender_id, recipient_id, recipient_id, sender_id)  end    def self.create_or_find_conversation(task_assigner_id, task_executor_id)    Conversation.between(task_assigner_id, task_executor_id).first_or_create do |conversation|      conversation.sender_id = task_assigner_id      conversation.recipient_id = task_executor_id    end  end  

conversation_spec.rb

describe "class methods" do      let(:sender) { create(:user) }    let(:recipient) { create(:user) }    let(:other_recipient) { create(:user) }    let!(:conversation) { create(:conversation, sender: sender, recipient: recipient) }      context "create_of_find_conversation" do       #this one throws Failure/Error: expect{conv}.to change{Conversation.count}.by(1)     #expected result to have changed by 1, but was changed by 0      it "creates conversation" do        conv = Conversation.create_or_find_conversation(sender, other_recipient)        expect{conv}.to change{Conversation.count}.by(1)      end        #this one is working as expected      it "finds conversation" do        conv = Conversation.create_or_find_conversation(sender, recipient)        expect(conv).to eq(conversation)      end    end  end  

Error when reseting passoword

Posted: 16 Apr 2016 04:58 AM PDT

If a user is invited, but instead of clicking the invitation they go to the site and try to login, they get a "email already taken" message. They then try to use the password reset to gain access and get the error:

undefined method `+' for nil:NilClass    bin/rails:    4 rescue LoadError => e  5  raise unless e.message.include?('spring')  6 end  7 APP_PATH = File.expand_path('../../config/application',  __FILE__)  8 require_relative '../config/boot'  9 require 'rails/commands'  

The password reset works correctly for regular users who were not added through the invite system.

What's going wrong with the invite system? or maybe a better question, how do i start to debug that? Since the line given on the better errors page (line 9) is probably not the actual line giving the error.

Rails generic not found controller method

Posted: 16 Apr 2016 07:15 AM PDT

In my controller I have this code in one of my actions:

begin    @user = User.find(params[:id])    @user.destroy  rescue ActiveRecord::RecordNotFound    render :json => {"status" => "404", "message" => "User with id #{params[:id]} not found"}    return  end  

And is working fine, but I dont want to copy paste it to all the methods which require to run a Select query.

So I found this answer How to redirect to a 404 in Rails?

And then tried slightly different since I am rendering JSON API endpoints instead templates. Note also I dont know if that params[:id] will be defined there.

  def not_found      render :json => {"status" => "404", "message" => "User with id #{params[:id]} not found"}    end  

Anyway I modified the query with:

@user = User.find(params[:id]) or not_found  

But is still raising the ActiveRecord::RecordNotFound exception.

Also would it be possible to create a generic not_found action which I can use in all the controllers which I can pass it the id parameter and the type of the Object?

Like some generic 404, 500, 400, 200 methods which render JSON responses where I can just pass some parameters

Ruby to Java code translation [on hold]

Posted: 16 Apr 2016 04:22 AM PDT

So i have a few algorithms to convert from ruby to java and as I've never done Ruby before I am not familiar with the syntax and functionality of ruby. I have begun to research ruby and am a bit more learned on a few aspects of it but would appreciate if someone could convert the following to java so I can learn from this one and apply to the other similar algorithms that I need to convert.

def euc_2d(c1, c2)  Math.sqrt((c1[0] - c2[0])**2.0 + (c1[1] - c2[1])**2.0).round  end    def cost(perm, cities)  distance =0  perm.each_with_index do |c1, i|  c2 = (i==perm.size-1) ? perm[0] : perm[i+1]  distance += euc_2d(cities[c1], cities[c2])  end  return distance  end    def stochastic_two_opt(permutation)  perm = Array.new(permutation)  c1, c2 = rand(perm.size), rand(perm.size)  exclude = [c1]  exclude << ((c1==0) ? perm.size-1 : c1-1)  exclude << ((c1==perm.size-1) ? 0 : c1+1)  c2 = rand(perm.size) while exclude.include?(c2)  c1, c2 = c2, c1 if c2 < c1  perm[c1...c2] = perm[c1...c2].reverse  return perm  end    def local_search(best, cities, max_no_improv)  count = 0  begin  candidate = {:vector=>stochastic_two_opt(best[:vector])}  candidate[:cost] = cost(candidate[:vector], cities)  count = (candidate[:cost] < best[:cost]) ? 0 : count+1  best = candidate if candidate[:cost] < best[:cost]  end until count >= max_no_improv  return best  end    def construct_randomized_greedy_solution(cities, alpha)  candidate = {}  candidate[:vector] = [rand(cities.size)]  allCities = Array.new(cities.size) {|i| i}  while candidate[:vector].size < cities.size  candidates = allCities - candidate[:vector]  costs = Array.new(candidates.size) do |i|  euc_2d(cities[candidate[:vector].last], cities[i])  end  rcl, max, min = [], costs.max, costs.min  costs.each_with_index do |c,i|    rcl << candidates[i] if c <= (min + alpha*(max-min))  end  candidate[:vector] << rcl[rand(rcl.size)]  end  candidate[:cost] = cost(candidate[:vector], cities)  return candidate  end    def search(cities, max_iter, max_no_improv, alpha)  best = nil  max_iter.times do |iter|  candidate = construct_randomized_greedy_solution(cities, alpha);  candidate = local_search(candidate, cities, max_no_improv)  best = candidate if best.nil? or candidate[:cost] < best[:cost]  puts " > iteration #{(iter+1)}, best=#{best[:cost]}"  end  return best  end    if __FILE__ == $0  # problem configuration  berlin52 = [[565,575],[25,185],[345,750],[945,685],[845,655],  [880,660],[25,230],[525,1000],[580,1175],[650,1130],[1605,620],  [1220,580],[1465,200],[1530,5],[845,680],[725,370],[145,665],  [415,635],[510,875],[560,365],[300,465],[520,585],[480,415],  [835,625],[975,580],[1215,245],[1320,315],[1250,400],[660,180],  [410,250],[420,555],[575,665],[1150,1160],[700,580],[685,595],  [685,610],[770,610],[795,645],[720,635],[760,650],[475,960],  [95,260],[875,920],[700,500],[555,815],[830,485],[1170,65],  [830,610],[605,625],[595,360],[1340,725],[1740,245]]  # algorithm configuration  max_iter = 50  max_no_improv = 50  greediness_factor = 0.3  # execute the algorithm  best = search(berlin52, max_iter, max_no_improv, greediness_factor)  puts "Done. Best Solution: c=#{best[:cost]}, v=#{best[:vector].inspect}"  end  

I assume that in Ruby data types such as int double etc are not specified so in order to convert into java the necessary types need to be addressed and then. If possible to please add comments on the reasoning of changes so I would know why. Thanks in advance to all who help.

Update via array

Posted: 16 Apr 2016 03:24 AM PDT

I have a trouble in update. When I submit the form, the parameter gives me an Hash of values like {"1"=>"1", "4"=>"1"}. I want only the values to be updated. So, I have separated the Keys and Values keys, values = @period.map { |k,v| [k.to_i, v.to_i] }.transpose where @period = {"1"=>"1", "4"=>"1"}. where I get the values like [1,4]. So, How can I update it via this array. when I use update_attributes only the last value(4). How can I update the fields via array. I am new to rails , so be calm.

Listing users online

Posted: 16 Apr 2016 05:31 AM PDT

In this question I asked how to list out users currently online in the chat. While discussing I was given an answer, and I tried to implement it, but I didn't succeed. So, I made a migration add_last_online_to_users last_online:datetime and made a tweak in User model:

user.rb:

def self.online_now    where ("last_online > ?", 15.minutes.ago)  end  

And then added to my Message controller, so that each time an user sends a message, his last_online updates to Time.now. Finally, I added to my application_controller the following code:

def show_online    @users = User.online_now  end  

and called that method in my view:

<% @users.each do |user| %>      <%= user.show_online %>  <% end %>  

that returned me a NoMethodError: undefined method 'each' for nil:NilClass

Rails time table update form

Posted: 16 Apr 2016 03:51 AM PDT

My project has day calender
where period model has period_id(id autoincrement) and subject,teacher_id,which_period ,day.

output will be update form like below

data in form below as follows (period_id ,which_period ,day) = hidden ,subject is input field .

how to achieve this please help ...

----------------------------------------------------------  |period|        1        |        2        |       3  ----------------------------------------------------------  | mon  |  period_id=1    |   period_id=2   | period_id=3  |      | which_period =1 | which_period =2 | which_period =3  |      |      day=mon    |     day=mon     | day=mon  |      |  subject   =1   |   subject  =2   | subject =3 <= input_field  ----------------------------------------------------------  | tue  |  period_id=4    |   period_id=5   |  period_id=6  |      |      day=tue    |     day=tue     |    day=tue  |      | which_period =1 | which_period =2 | which_period =3  |      | subject   =4    | subject   =5    | subject   =6  ----------------------------------------------------------                                            | submit|  ---------------------------------------------------------

view code

    <%= form_for @period, url: welcome_update_path  do |f| %>        <%= 6.times do %>             <%= f.hidden :period_id %>             <%= f.hidden :day %>             <%= f.hidden :which_period %>             <%= f.text_field :subject %>         <%= end %>        <%= f.submit "Create" %>      <% end %>

controller code

    def update          @period = Period.find(params[:id])           if @period.update(perio_params)            flash[:notice]='success'          end      end      private          def perio_params              params.require(:period).permit(  :subject  , :day, :which_period)          end

thanks

How to access a property from belongs_to model from a scope

Posted: 16 Apr 2016 03:15 AM PDT

I have 2 models in my app: Person and Review each person has many reviews and each review belongs to a person. I have an attribute called grade inside of my review model and I'd like to display the average grade of each person so I wrote this scope:

scope :average_grade, -> { self.first.review.average(:grade) }  

Is there a better way for doing that? Besides the 2 queries that this method needs, I also have to run another 2 queries to get the proper Person object in my controller:

def show    @average = Person.includes(:review).where(id: params[:id]).average_grade    @person =  Person.includes(:review).find(params[:id])  end  

How could I avoid all of those queries?

rails update multiple records in single model and single form

Posted: 16 Apr 2016 03:15 AM PDT

iam new to rails, i have model(welcome) and i want to update the model with single form where the form has duplicate fields . only second field updates the model ..

Update multiple records in single model with single form_submit

routes

  get 'welcome/index'    get 'welcome/new'    post 'welcome/create'    root 'welcome#index'
welcomecontroller
class WelcomeController < ApplicationController    def index    end    def new      @article = Welcome.new    end    def create      @article = Welcome.new(user_params)      if @article.save        redirect_to welcome_new_path      else        render 'new'      end    end        private        def user_params      params.require(:welcome).permit(:name , :descrip  )    end  end
welcomeindex view
<%= form_for@ article, url: welcome_create_path do |f | %>    <%= f.text_field: name %>    <%= f.text_field: descrip %>    <%= f.text_field: name %>    <%= f.text_field: descrip %>    <%= f.submit "Create" %>  <% end %>
thanks

How to use Rails connection which is manually checkout

Posted: 16 Apr 2016 04:59 AM PDT

I have code which where I manually checkout a connection like

connection = User.connection_pool.checkout

Now, I wish to use this connection to query any record in DB

is there a way to achieve this.

I'm not sure what I'm suppose to do with the connection, I just obtained other then checking it back in

So ideally I want the code do this.

  connection = User.connection_pool.checkout    ... ## query      User.connection_pool.checkin(connection)  

Note: Please don't answer me to use with_connection, the point of this question is to manage checkout/checkin manually.

Any clue ??

Displaying the attributes of another table

Posted: 16 Apr 2016 05:39 AM PDT

I have two models: User and Role. The User attributes are:

name:string  email:string   admin:boolean   role_id:integer  

The Role attributes are:

designer:boolean   developer:boolean  

The associations that I've set is that user belongs_to role and role has_many users. When the user signs up, I want him to choose his position (either designer or developer). However, I get the role_id as an Integer field when I want to display the positions (designer and developer) to choose from. Can anyone help me with that?

Helper date_select. How validate dates 30 and 31 of february?

Posted: 16 Apr 2016 02:11 AM PDT

I have model Freelancer and tables freelancers with property birthday, type date.

freelancers/edit.html.erb

<li class="form-fields__group form-fields__group_birthdate">          <label for="freelancer_birth_date">Birthday</label>          <div class= "field">            <%= f.date_select :birthday, { prompt: { day: 'Select day',                                                     month: 'Select month',                                                     year: 'Select year' },                                  include_blank: true, start_year: Time.now.year - 70},                                                       { class: 'form-control_medium'} %>          </div>        </li>  

If I selcet february 30 or 31 return value 3 march. How me validate value date 30 and 31 if I selected february? Thank you

How can I dynamically add ckeckboxes to my Rails form?

Posted: 16 Apr 2016 06:06 AM PDT

As you can see I have my main Car form (created with the Form Object) and the form of the Wheel with it's own inputs, images etc. It likes nested in my car form. When I select checkboxes wheels became added to my car.

How can I dynamically add ckeckboxes to my Car form based on the wheel form?

Associations are such: Car has_and_belongs_to_many wheels

enter image description here

NoMethodError (undefined method `id' for nil:NilClass)

Posted: 16 Apr 2016 02:11 AM PDT

I'm getting this error when I request via cURL to create a ticket on Redmine. My cURL is creating the ticket successfully but it's is also returning an error and I'm not able to understand why is it so.

Here's the error I'm getting:

Started POST "/issues.json" for 122.161.50.0 at 2016-04-16 07:18:22 +0000  Processing by IssuesController#create as JSON  Parameters: {"issue"=>{"project_id"=>10, "tracker_id"=>7, "status_id"=>1, "priority_id"=>3, "subject"=>"Issue created from CURL"}}  Current user: himanshu (id=3)  Rendered mailer/_issue.text.erb (6.8ms)  Rendered mailer/issue_add.text.erb within layouts/mailer (45.6ms)  Rendered mailer/_issue.html.erb (2.3ms)  Rendered mailer/issue_add.html.erb within layouts/mailer (6.9ms)  Completed 500 Internal Server Error in 724.8ms    NoMethodError (undefined method `id' for nil:NilClass):  lib/redmine/hook.rb:61:in `block (2 levels) in call_hook'  lib/redmine/hook.rb:61:in `each'  lib/redmine/hook.rb:61:in `block in call_hook'  lib/redmine/hook.rb:58:in `tap'  lib/redmine/hook.rb:58:in `call_hook'  lib/redmine/hook.rb:153:in `call_hook'  app/controllers/issues_controller.rb:151:in `create'  

This is the controller code

def create  call_hook(:controller_issues_new_before_save, { :params => params, :issue => @issue })  @issue.save_attachments(params[:attachments] || (params[:issue] && params[:issue][:uploads]))  if @issue.save    call_hook(:controller_issues_new_after_save, { :params => params, :issue => @issue})    respond_to do |format|      format.html {        render_attachment_warning_if_needed(@issue)        flash[:notice] = l(:notice_issue_successful_create, :id => view_context.link_to("##{@issue.id}", issue_path(@issue), :title => @issue.subject))        if params[:continue]          attrs = {:tracker_id => @issue.tracker, :parent_issue_id => @issue.parent_issue_id}.reject {|k,v| v.nil?}          redirect_to new_project_issue_path(@issue.project, :issue => attrs)        else          redirect_to issue_path(@issue)        end      }      format.api  { render :action => 'show', :status => :created, :location => issue_url(@issue) }    end    return  else    respond_to do |format|      format.html { render :action => 'new' }      format.api  { render_validation_errors(@issue) }    end  end  end  

This is the code that calls a hook

def call_hook(hook, context={})      [].tap do |response|        hls = hook_listeners(hook)        if hls.any?          hls.each {|listener| response << listener.send(hook, context)}        end      end    end  

Uppercase variable scope in Rails

Posted: 16 Apr 2016 01:45 AM PDT

If for example I used this line to generate a model:

bin/rails generate model Item Collection:references  

Then it will generate this kind of migration with the uppercase reference variable:

class CreateItems < ActiveRecord::Migration    def change      create_table :items do |t|        t.references :Collection, index: true          t.timestamps      end    end  end  

And this generates a Collection_id field in the table with the uppercase.

The problem is I want now to add a Scope, to filter Items by Collection_id from the controller:

So I created this scope in the Item's model scope :collection_id, -> (Collection_id) { where collection_id: Collection_id }

But when I call it in the controller with: @items = Item.collection_id(@user.Collection_id)

It crashes with:

formal argument cannot be a constant scope :collection_id, -> (Collection_id) { where collection_id: Collection_id } ^

I read in the scope the variable cannot be an uppercase variable but since the migration is creating them by default that way I dont know if this is intended or I am doing it wrong.

make gem specific version default for all environment [Ruby on Rails]

Posted: 16 Apr 2016 12:50 AM PDT

when I ran gem list I get two different versions of gems I've installed:

bigdecimal (1.2.7, default: 1.2.6)  io-console (0.4.5, default: 0.4.3)  json (1.8.3, default: 1.8.1)  lunchy (0.10.4)  psych (2.0.17, default: 2.0.8)  rake (11.1.2, default: 10.4.2)  rdoc (4.2.2, default: 4.2.0)  

How can I set rake 11.1.2 as default? this is not for a particular projet but my gems in general, so there's no Gemfile.

Thanks in advance.

rails - undefined method `model_name'

Posted: 16 Apr 2016 01:36 AM PDT

I have a basic blogging site in which I want to allow users to offer 'corrections' to posts (just think of it as a comment). The correction object belongs to a post, which in turn belongs to a user (for which I'm using Devise).

I would like the form to create a new correction to be nested in the page for the post,so I'm just rendering the form in posts/show.html.erb with <% render :template => "corrections/new" %>. I'm getting a 'undefined method model_name' error from the line form_for line in corrections/new.html.erb though.

Here's the form:

<% form_for [@correction, :url=> user_post_corrections_path(current_user, @post, @correction)], html: { multipart: true} do |f| %>    <div class="field">      <%= f.label :correction %>      <%= f.text_field :correction %>    </div>    <div class="actions">      <%= f.submit %>    </div>  <% end %>  

Here's the corrections_controller:

class CorrectionsController < ApplicationController      def new      @post = Post.find(params[:post_id])      @correction = current_user.@post.corrections.build      respond_with(@correction)    end      def create      @post = Post.find(params[:post_id])      @correction = current_user.@post.corrections.build      if @correction.save        redirect_to user_post_path(current_user, @correction.post_id)      end    end  end  

In my routes.rb:

  resources :users do      resources :posts do        resources :corrections        end      end  

Any help with this would be much appreciated.

Crawl page which requires login with Anemone

Posted: 16 Apr 2016 12:26 AM PDT

I'm using Anemone gem in following way:

  • Visit first url (seed), save page content to database and save all links from this page to database as well (all links which are not in database yet)
  • Load next link from database, save its content and any other links again
  • If there is no other link, crawl all links again (after some time period) to overwrite old content by new

This works pretty well but is there any possibility how to crawl pages which requires login (if I know username and password)? I know Mechanize gem which provide functionality to fill in forms but I don't know how to integrate it in my process (if it is possible). Or is there any other way how to crawl pages "behind" login form?

rails 4 stripe js showing live mode when in test mode

Posted: 16 Apr 2016 12:21 AM PDT

I have been researching this and for some reason I am turning up a blank. As you can see from the attached segments below I am running in testing mode and when I try to use the testing stripe cards specifically 4242424242424242 nothing is working. Thoughts? Pointers?

Console log of the stripe error...

enter image description here

Stripe Interface...

enter image description here

The javascript code in progress...

    function process_payment(cardNumber, cardExpiration, cardVerification, zipCode, price){        var vpf = validate_payment_fields();        if(vpf === true){          process_stripe_api(cardNumber, cardExpiration, cardVerification, zipCode, price);          // $contentLoader.show();          // clear_cc_fields($cardNumber, $cardExpiration, $cardVerification, $zipCode);          // $paymentProcessorForm.submit();        }      }        function process_stripe_api(cardNumber, cardExpiration, cardVerification, zipCode, price){        Stripe.createToken({          number: cardNumber,          cvc: cardVerification,          exp_month: cardExpiration.substring(0,2),          exp_year: cardExpiration.substring(3,5),          price: price        }, stripeResponseHandler);      }        function stripeResponseHandler(status, response) {        if (response.error) {          debugger;        }        else {          console.log('passed!');          debugger;        }      }        function validate_payment_fields(){        var $cardNumber = jQuery('#card_number');        var $cardVerification = jQuery('#card_verification');        var $cardExpiration = jQuery('#card_expiration');        var $zipCode = jQuery('#zip_code');          $cardNumber.next('.help-error').remove();        $cardVerification.next('.help-error').remove();        $cardExpiration.next('.help-error').remove();        $zipCode.next('.help-error').remove();          trim_field($cardNumber);        var cardNumber = validate_card_number($cardNumber);          trim_field($cardExpiration);        var cardExpiration = validate_card_expiration($cardExpiration);          trim_field($cardVerification);        var cardVerification = validate_card_verification($cardVerification);          trim_field($zipCode);        var zipCode = validate_zipcode($zipCode);          if(cardNumber && cardExpiration && cardVerification && zipCode){          return true;        }        else{          return false;        }      }        function clear_cc_fields(cardNumber, cardExpiration, cardVerification, zipCode){        cardNumber.val('');        cardVerification.val('');        cardExpiration.val('');        zipCode.val('');      }        function validate_card_number(field){        var regTester = new RegExp("\\d{16}");        if(regTester.test(field.val())){          return true;        }        else{          field.after("<p class='help-error'>Credit Card Number is Invalid!</p>");          return false;        }      }       function validate_card_expiration(field){        var regTester = new RegExp("^((0[1-9])|(1[0-2]))\/((2009)|(20[1-2][0-9]))$");        if(regTester.test(field.val())){          return true;        }        else{          field.after("<p class='help-error'>Credit Card Expiration is Invalid!</p>");          return false;        }      }        function validate_card_verification(field){        var regTester = new RegExp("\\d{3}");        if(regTester.test(field.val())){          return true;        }        else{          field.after("<p class='help-error'>CCV is Invalid!</p>");          return false;        }      }        function validate_zipcode(field){        var regTester = new RegExp("\\d{5}");        if(regTester.test(field.val())){          return true;        }        else{          field.after("<p class='help-error'>Zip Code is Invalid!</p>");          return false;        }      }        function trim_field(field){        var tmp = jQuery.trim(field.val());        field.val(tmp);        return tmp;      }  

A snippet from the view...

= javascript_include_tag 'https://js.stripe.com/v2/'    javascript:    Stripe.setPublishableKey("#{ENV['MY_STRIPE_PUBLISHABLE_KEY']}");  

The form...

enter image description here

How to install django cors on server host computer

Posted: 16 Apr 2016 12:23 AM PDT

I developed a webapp using Django framework and hosted it on Digital Ocean. The server is supposed to receive a Json from a client written using Ruby rails framework.

The Django app cannot see the Json and so I want use django-cors-headers https://github.com/ottoyiu/django-cors-headers which require me to install django-cors-headers, but I have already hosted the app (i.e. the server).
My questions are ( sorry I am newbie)

  1. Is it possible to install django-cors-headers using the pip install django-cors-headers on the server host computer at Digital Ocean using may be PUTTY or Winscp? If yes, pls how do i do it?
  2. Did I choose the right solution to my problem?

Below is the code for the server (views.py) and I am using Django 1.9 and python 2.7.6

from django.shortcuts import render  from django.http import HttpResponse  from django.http import JsonResponse  import json  def qucserver (request):  if request.method == 'POST':     print request.body     jsdata = json.loads(request.body)     reply = {"data": jsdata}     return JsonResponse  ( reply )  else:      message = 'You submitted an empty form.'      reply = {"Error": message}      return JsonResponse (reply)  

The output is always

  {data: "json = JSON_DATA"}  

No comments:

Post a Comment