Friday, November 18, 2016

SendGrid HTTP API put on job queue | Fixed issues

SendGrid HTTP API put on job queue | Fixed issues


SendGrid HTTP API put on job queue

Posted: 18 Nov 2016 07:44 AM PST

I'm using the sendgrid-ruby gem and i'd like to put the job on the queue. I'm using delayed job for background jobs.

sg   = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])  sg.delay.client.mail._('send').post(request_body: data)  

adding delay throws an error when added anywhere in the chain of method calls on sg.

undefined method 'mail' for #<Delayed::Backend::ActiveRecord::Job:>

how can I put this job on the queue?

Match user permissions against request in CanCan

Posted: 18 Nov 2016 07:39 AM PST

In my Rails app, a user can have multiple roles, and roles have multiple permissions.

The permissions table looks like: id, name, resource, action, description

An example might be:

id: 1,  name: 'add_article'  resource: 'Article'  action: 'new'  description: 'Add a new article'  

What I want to do is map this to the new method in my ArticlesController.

In my Ability.rb class in models I have:

class Ability    include CanCan::Ability      def initialize(user)        if user        user.roles.each do |role|          role.permissions.each do |permission|            can ACTION, RESOURCE          end        end      end      end    end  

So I basically need to match the permission against the resource requested... How do I do this?

How do I name parameters in my view so that an array gets built when I submit my form?

Posted: 18 Nov 2016 07:31 AM PST

I'm using Rails 5. I have this model

class Scenario < ApplicationRecord    belongs_to :grading_rubric, optional: true    has_many :confidential_memo    has_many :scenario_roles, :dependent => :destroy    has_many :roles, :through => :scenario_roles      …    accepts_nested_attributes_for :roles  end  

I'm dynamically creating role elements in my view, but am having trouble getting them all processed when they are submitted. I submit the following form from the client

.   utf8:✓  .   authenticity_token:n2/51OSHlNP+1E7qnLku/gXtCjUk/MfMxwsrNpUirR2IbQddOzP1/OClL50ClCPvDNIowvdsqpVNmer37Egp4w==  .   scenario[title]:title #8  .   scenario[abstract]:abstract  .   scenario[roles][name]:wwz  .   scenario[roles][name]:aaa  .   authenticity_token:n2/51OSHlNP+1E7qnLku/gXtCjUk/MfMxwsrNpUirR2IbQddOzP1/OClL50ClCPvDNIowvdsqpVNmer37Egp4w==  

See that I have two different parameters with the name "scenario[roles][name]". But on the server end, it only picks up one of the two parameters. Here is what is in my log ...

Parameters: {"utf8"=>"✓", "authenticity_token"=>"n2/51OSHlNP+1E7qnLku/gXtCjUk/MfMxwsrNpUirR2IbQddOzP1/OClL50ClCPvDNIowvdsqpVNmer37Egp4w==",    "scenario"=>{"title"=>"title #8", "abstract"=>"abstract", "roles"=>{"name"=>"aaa"}}}  

What do I need to name my parameters in my view so that multiple ones get picked up on my server?

Data is not displaying in phpmyadmin sql table

Posted: 18 Nov 2016 07:16 AM PST

I have created model and added 10 rows successfully from rails application. I can access it using Model name. But if i go to my local database and click on the table i am getting zero rows. Can anyone help me in this?

Paper Trail methods missing

Posted: 18 Nov 2016 06:58 AM PST

I'm applying Paper Trail to this model.

class Challenge < ActiveRecord::Base    include FriendlyId    friendly_id :challenge, use: :slugged    has_paper_trail :ignore => [:created_at, :updated_at, :page_views, :description, :rules, :prizes, :resources, :evaluation, :license]    .    .  end  

The data has been correctly added to the versions table. enter image description here

But some commands don't seem to be working.

c = Challenge.find(3)  (OK) c.versions.length   => 7   (OK) c.versions.last.whodunnit => "1"  (OK) c.version => nil     (FAIL) c.paper_trail.live?  NoMethodError: undefined method `paper_trail' for #<Challenge:0x007fdb4145c9b8>  

This doesn't work either

c.versions.last.paper_trail.live?  NoMethodError: undefined method `paper_trail' for #<PaperTrail::Version:0x007fdb41416eb8>  

fields_for and child_index with a serialized hash

Posted: 18 Nov 2016 06:40 AM PST

I have an attribute on an ActiveRecord object that I'm using to store a serialized hash (a response to a an ever-changing questionnaire). I've chosen to do it this way (rather than create an association) because I need to preserve the exact question asked at the time of submittal.

class Submission < ActiveRecord::Base    serialize :part_1, Hash  end  

I'm using my controller to build the hash like this:

def new    @submission = Submission.new    @submission.part_1 = Question.visible.ordered.each_with_object({}) { |r, h| h[r.order] = { answer: nil, question: r.text } }  end  

What I'd like to know is why this doesn't give me a field name of submission[part_1][0][answer]:

<%= bootstrap_form_for(@submission, {  }) do |f| %>    <% @submission.part_1.each do |order, value| %>      <%= f.fields_for(:part_1, value, { child_index: order.to_s }) do |p| %>        <%= p.text_area(:answer, { label: { text: value[:question] }, value: value[:answer] }) %>      <% end %>    <% end %>      <%= f.primary %>    <%= link_to(:Cancel, submissions_path, { class: 'btn btn-primary' }) %>  <% end %>  

It just gives me a field name of submission[part_1][answer]. I had thought the child_index options would be enough, but it isn't. I can get the field name I need with this change:

<%= p.text_area("#{order}][answer", ...  

But that just seems ugly.

Postgres/ActiveRecord select as not generating dynamic column

Posted: 18 Nov 2016 06:46 AM PST

I'm running into a bit of trouble with what I thought was a straight forward enough Postgresql/ActiveRecord query.

I have courses that have many sessions. Date/Time info rests with the sessions. I need to get all the records that start after now based on the association values. I tried the following query but postgres returns an error saying the dynamically generated dmin column doesn't exist?

Course.where(is_active: true).joins(:sessions).select("min(sessions.start_time) AS dmin").where("dmin > ? AND sessions.start_time < ?", Time.now, Time.now.end_of_month + 2.month)  

Self-referencing association with copy in Rails

Posted: 18 Nov 2016 06:27 AM PST

I'm looking for a proper way to make a specific self-referential association.

I have a Test model (users are taking part in classes and they try to pass tests). In case user does not pass the test I'd like to have a copy of this test and possibility to see in the original test all next attempts (copies) and in copies of original I'd like to see the id of the original test.

I already tried few things with self-referencing, however without luck.

test.rb

    has_many :retestizations      has_many :retests, through: :retestizations  

retestization.rb

    belongs_to :original, class_name: 'Test', foreign_key: 'original'      belongs_to :copy, class_name: 'Test', foreign_key: 'copy'  

migration:

    def change          create_table :retestizations do |t|            t.integer :original            t.integer :copy              t.timestamps null: false          end        end  

Any ideas? :)

Pass values from select_tag in params

Posted: 18 Nov 2016 07:46 AM PST

I created a "select_tag" field and I need it when the user clicks save all the values of this field to be passed by params to the controller. The problem is that when I click save, only the first value entered in this field is passed to the controller.

To better understand, the "select_tag" field is populated through another field, the "f.text_field :members" field. When I click on an "add" button the value of the "f.text_field :members" field is passed to the "select_tag" field and so I want to be able to check all these values from the "select_tag" field to validate and save, how do I do that? As I already said, only the first value entered is passed.

Code:

<%= form_for(@focus_group) do |f| %>    <% if @focus_group.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@focus_group.errors.count, "error") %> prohibited this focus_group from being saved:</h2>          <ul>        <% @focus_group.errors.full_messages.each do |message| %>          <li><%= message %></li>        <% end %>        </ul>      </div>    <% end %>    <script type="text/javascript">    $(function() {      $('#focus_group_moderator, #focus_group_members').autocomplete({        source: '/focus_groups/autocomplete.json'      });    });    function add(){      var value = $('#focus_group_members').val();      var select = document.getElementById("membersAdded");      var option = document.createElement("option");      option.text = value;      option.value = value;      select.add(option);        $('#focus_group_members').val("");    }      function removeFromSelect(){      var select = document.getElementById("membersAdded");      select.remove(select.selectedIndex);    }    </script>    <div class="field">      <%= f.label :name %><br>      <%= f.text_field :name %>    </div>    <div class="field">      <%= f.label :topic %><br>      <%= f.text_field :topic %>    </div>    <div class="field">      <%= f.label :moderator %><br>      <%= f.text_field :moderator %>    </div>    <div class="field">      <%= f.label :description %><br>      <%= f.text_area :description %>    </div>    <div class="field">      <%= f.label :members %><br>      <%= f.text_field :members %>      <input onclick="add()" type="button" value="Add" /><br>      <%= select_tag(:membersAdded, options_for_select([])) %>      <input onclick="removeFromSelect()" type="button" value="Remove" /><br>      <br>    </div>    <div class="actions">      <%= f.submit %>    </div>  <% end %>  

CONTROLLER

class FocusGroupsController < ApplicationController    before_action :set_focus_group, only: [:show, :edit, :update, :destroy]    include FocusGroupsHelper      def index      if(params[:term])        @profile = Profile.all.select("name", "id")          @lista = Array.new          @profile.each do |x|          @lista.push(x.name)        end          respond_to do |format|          format.html          format.json { render json: @lista.to_json}        end      else        @focus_groups = FocusGroup.all      end    end      def show    end      def new      @focus_group = FocusGroup.new      @membersAdded        respond_to do |format|        format.html        format.json { render json: Profile.all.to_json}      end    end      def edit    end      def create      @moderator= find_profiles_id(focus_group_params[:moderator])      @moderator.each do |f|        @moderator_id = f.id      end        @params = focus_group_params      @params[:moderator] = @moderator_id        @focus_group = FocusGroup.new(@params)        if @focus_group.save        redirect_to @focus_group, notice: 'Focus group was successfully created.'      else        render :new      end    end      def update      if @focus_group.update(focus_group_params)        redirect_to @focus_group, notice: 'Focus group was successfully updated.'      else        render :edit      end    end      def destroy      @focus_group.destroy      redirect_to focus_groups_url, notice: 'Focus group was successfully destroyed.'    end      def autocomplete      if(params[:term])        @profile = Profile.all.where("user_id <> 0 and is_template = 'f' and name LIKE ?", "#{params[:term]}%").select("name", "id")          @lista = Array.new          @profile.each do |x|          @lista.push(x.name)        end          respond_to do |format|          format.html          format.json { render json: @lista.to_json}        end      end    end      def find_profiles_id(name)      return Profile.all.where("name LIKE ?", "#{name}%").select("id")    end      def find_profiles_name(id)      @profile = Profile.all.where("id = ?", "#{id}").select("name")        @profile.each do |e|        @name = e.name      end      return @name    end      private        def set_focus_group        @focus_group = FocusGroup.find(params[:id])      end        def focus_group_params        params.require(:focus_group).permit(:name, :topic, :moderator, :description, :members, :membersAdded)      end  end  

Nginx API subdomain

Posted: 18 Nov 2016 06:28 AM PST

I've just created sub-domain for API usage. Now it looks like api.example.com and everything works fine. However I would like to forbit access to html views from api.example.com. It should response on api calls only.

scope module: 'web' do      root 'home#index'  end    constraints subdomain: 'api' do      scope module: 'api' do          scope module: 'v1' do            end      end  end  

I guess I can achieve it via build appropriate location directive

server {          listen 80;          listen [::]:80;            rails_env production;          root /home/example/current/public;            server_name api.example.com;          #location ???  }  

Below block for example.com domain:

server {            listen 80;            listen [::]:80;              rails_env production;            root /home/example/current/public;              server_name example.com;            error_page   500 502 503 504  /50x.html;              location = /50x.html {                root   html;            }    }  

How can I achieve that?

Pass link back to notice in Rails

Posted: 18 Nov 2016 05:49 AM PST

In my Rails app I want to pass back link to the notice from the controller.

e.g.

redirect_to permalinks_path, :notice => "Permalinks updated! You will want to update the #{link_to 'Site map', sitemap_path} too!"  

However I get an error:

undefined method `link_to' for #<SettingsController:0x007fda280480f8>  

How can I solve this?

Ruby on rails : undefined method 'map' for #<String>

Posted: 18 Nov 2016 06:27 AM PST

I am trying to create a rails form using and tag, but I want to generate options with a json file, because I want all the countries. But I have this error :

undefined method `map' for #<String:0x007f871472e9b0>   

Here is my application_helper.rb :

module ApplicationHelper    def countries_for_select      file = File.read(File.join(Rails.root, 'app', 'helpers', 'countries.json')).to_json      countries = JSON.parse(file)      countries.map {|c| [ c['country']['name'], v['country']['code'] ] }    end  end  

Here is my posts_controller.rb :

  def create      countries_for_select      @post = Post.new(posts_params)      @post.user = current_user      options_for_countries      if @post.save        flash[:success] = "Your post have been published"        redirect_to post_show_path      else        render 'new'      end    end  

Here is the line in my _form.html.erb file :

<%= select_tag(:country, countries_for_select) %>  

So I don't understand why it doesn't work, Does someone could help me ?

Thank you !

How to save current_user email and show it to the user?

Posted: 18 Nov 2016 05:23 AM PST

I am making rails blog and I want to make functionality where comment author can be anonymous or current_user depending of if its signed in or not.

How can I save current_user email and show it to the user? I guess I didn't connected user and comment properly?

When I try to save comment, I get user must exist error. When I set user_id manually, @commenter is empty.

This is comments controller:

class CommentsController < ApplicationController      def new      @post = Post.find(params[:post_id])      @comment = @post.comments.new(comment_params)      @user = current_user if user_signed_in?    end      def create      @post = Post.find(params[:post_id])      @comment = @post.comments.build(comment_params)        if user_signed_in?        @user = current_user        @user.id = current_user.id        @user.comments.build(comment_params)        @commenter = @user.email      end        if @comment.save        flash[:success] = "Successfuly created comment!"        redirect_to post_path(@post)      else        render :new      end    end      def destroy      @post = Post.find(params[:post_id])      @comment = @post.comments.find(params[:id])      @comment.destroy        redirect_to post_path(@post)    end      private    def comment_params      params.require(:comment).permit(:text)    end  end  

I have this in partial and it doesn't work, why??

<%= @commenter %>  

As for models: Comment belongs_to User and Post. User and Post has_many comments.

This is show.html.erb for post where comment partial is rendered:

...  <%= render @post.comments %>  <%= render 'comments/form' %>  

What am I doing wrong?

Rails Cucumber How to check if user is logged in before going to editing page

Posted: 18 Nov 2016 04:55 AM PST

I have developed Rails application where user needs to be logged in to edit character he created earlier. Now I am trying to test my edit character function and I have created edit character scenario. Here is my files:

features/character.feature

     Feature: Character           @javascript         Scenario: Visiting characters listing page           Given I am a new, authenticated user           When I go to characters index page           Then I should see characters listing page     

characters_steps.rb

   Given /^I am a new, authenticated user$/ do       email = 'ademimisel@gmail.com'       password = 'pass1234'         visit '#/login'       fill_in 'email', :with => email       fill_in 'password', :with => password       click_button "Sign in"     end      When(/^I go to characters index page$/) do      visit '#/'      expect(page).to have_content("Characters")    end      Then(/^I should see characters listing page$/) do      pending # Write code here that turns the phrase above into concrete     actions    end  

When I run, first step pass successfully but second not, because cucumber not register that sign up was successfully done and page are not redirected to edit page

How to include a 'next if' condition in an inline loop

Posted: 18 Nov 2016 06:29 AM PST

I would like to include next if in this loop:

 = select_tag :type, options_for_select(Products.statuses.keys.map{ |product_type| [I18n.t("product.#{product_type}"), product_type] }, params[:type])  

So I would like something as:

 Products.statuses.keys.map{ |product_type| next if product_type == "clothes", [I18n.t("product.#{product_type}"), product_type] }  

Rails, after I18n locale action via link_to, jquery unrecognized expression: /?locale=en

Posted: 18 Nov 2016 04:37 AM PST

When I click this link from myPage.html.erb:

<%=link_to 'English', url_for( :locale => 'en' ), :class=>"page-scroll color-me">  

My page reloads in my browser like this : http://myAdresse/?locale=en , and in my browser console I get this error:

jquery.self-aedf0b4….js?body=1:3  Uncaught Error: Syntax error, unrecognized expression: /?locale=en      fb.error    @   jquery.self-aedf0b4….js?body=1:3  fb.tokenize @   jquery.self-aedf0b4….js?body=1:3  fb.select   @   jquery.self-aedf0b4….js?body=1:3  fb  @   jquery.self-aedf0b4….js?body=1:3  find    @   jquery.self-aedf0b4….js?body=1:3  m.fn.init   @   jquery.self-aedf0b4….js?body=1:3  m   @   jquery.self-aedf0b4….js?body=1:3  (anonymous function)    @   agency.self-3998c07….js?body=1:12  dispatch    @   jquery.self-aedf0b4….js?body=1:4  r.handle    @   jquery.self-aedf0b4….js?body=1:4  

The adress of the file in my browser: http://myAdresse/assets/jquery.self-aedf0b4f9535e7b1d01d6a9ad81e6ecdb5b9a82acf17f3798645b7dbca2d86a1.js?body=1

Any idea why I got this error?

The funny thing is: if I hit F5, my whole page reloads (included jquery) and I have no error in my console anymore!

Any idea ?

Thanks

Rails redirect_to inside custom class

Posted: 18 Nov 2016 04:33 AM PST

I have a custom Class in my Rails application, which validates a bunch of settings.

The code:

class UserSettingObject < RailsSettings::SettingObject    validate do      if !/^([0-9]|0[0-9]|1[0]):[0-5][0-9]$/.match(self.time)        redirect_to settings_path, notice: 'Invalid time format'      end    end  end  

I check SO posts and found a similar problem (here), the recommendation was include ActionController::Redirecting but it doesn't works, resulting in undefined method `config_accessor' error.

How to use Rails redirects methods in a custom Class?

Coffeescript part being ignored

Posted: 18 Nov 2016 04:15 AM PST

In my rails application we have a login expiration time. If the user makes a request after being timed out we need to redirect him to the login page.

When we use remote links the login page should be a javascript code to update the location of the page.

If we use .js.erb extension it works as intended: the redirect will render Admin::SessionController#new as JS using the .js.erb file.

Started GET "/contato" for 127.0.0.1 at 2016-11-18 09:57:19 -0200  Processing by Admin::ContactController#show as JS    Parameters: {"subdomain"=>"admin"}  Redirected to http://admin.local.dev:3000/login  Filter chain halted as :restrict_admin_access rendered or redirected  Completed 303 See Other in 14ms (ActiveRecord: 0.0ms)    Started GET "/login" for 127.0.0.1 at 2016-11-18 09:57:20 -0200  Processing by Admin::SessionController#new as JS    Parameters: {"subdomain"=>"admin"}    Rendering admin/session/new.js.erb    Rendered admin/session/new.js.erb (5.2ms)  Completed 200 OK in 42ms (Views: 34.4ms | ActiveRecord: 0.0ms)  

But if we use the .coffee extension it will render the html version and there is no error log to explain the problem. Below is the log of such problem

Started GET "/contato" for 127.0.0.1 at 2016-11-18 09:41:34 -0200  Processing by Admin::ContactController#show as JS    Parameters: {"subdomain"=>"admin"}  Redirected to http://admin.local.dev:3000/login  Filter chain halted as :restrict_admin_access rendered or redirected  Completed 303 See Other in 74ms (ActiveRecord: 0.0ms)    Started GET "/login" for 127.0.0.1 at 2016-11-18 09:41:35 -0200  Processing by Admin::SessionController#new as JS    Parameters: {"subdomain"=>"admin"}    Rendering admin/session/new.html.erb    Rendered admin/session/new.html.erb (3659.3ms)  Completed 200 OK in 3846ms (Views: 3835.5ms | ActiveRecord: 0.0ms)  

If I remove the .html.erb file it also works as intended, but now I can't render the new action as html

Started GET "/contato" for 127.0.0.1 at 2016-11-18 09:58:45 -0200  Processing by Admin::ContactController#show as JS    Parameters: {"subdomain"=>"admin"}  Redirected to http://admin.local.dev:3000/login  Filter chain halted as :restrict_admin_access rendered or redirected  Completed 303 See Other in 9ms (ActiveRecord: 0.0ms)    Started GET "/login" for 127.0.0.1 at 2016-11-18 09:58:45 -0200  Processing by Admin::SessionController#new as JS    Parameters: {"subdomain"=>"admin"}    Rendering admin/session/new.coffee    Rendered admin/session/new.coffee (636.9ms)  Completed 200 OK in 668ms (Views: 659.3ms | ActiveRecord: 0.0ms)  

What is happening? Why the .coffee file is being ignored? How can I solve this?

The Admin::SessionController#new action:

def new    respond_to do |format|      format.js      format.html { redirect_to admin_root_url, turbolinks: true unless current_admin.nil? }    end  end  

EDIT

I've tried to open /login.js on the browser. This is the error output. If you pay attention the .html is being rendered and it is causing the error.

Started GET "/login.js" for 127.0.0.1 at 2016-11-18 10:12:18 -0200  Processing by Admin::SessionController#new as JS    Parameters: {"subdomain"=>"admin"}    Rendering admin/session/new.html.erb    Rendered admin/session/new.html.erb (6.1ms)  Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.  Completed 422 Unprocessable Entity in 44ms (Views: 22.9ms | ActiveRecord: 0.0ms)    ActionController::InvalidCrossOriginRequest (Security warning: an embedded <script> tag on another site requested protected JavaScript. If you know what you're doing, go ahead and disable forgery protection on this action to permit cross-origin JavaScript embedding.):    actionpack (5.0.0.1) lib/action_controller/metal/request_forgery_protection.rb:239:in `verify_same_origin_request'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:382:in `block in make_lambda'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:218:in `block in halting'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:456:in `block in call'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:456:in `each'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:456:in `call'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:101:in `__run_callbacks__'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'  actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:19:in `process_action'  actionpack (5.0.0.1) lib/action_controller/metal/rescue.rb:20:in `process_action'  actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'  activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument'  activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument'  activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument'  actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'  actionpack (5.0.0.1) lib/action_controller/metal/params_wrapper.rb:248:in `process_action'  activerecord (5.0.0.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action'  actionpack (5.0.0.1) lib/abstract_controller/base.rb:126:in `process'  actionview (5.0.0.1) lib/action_view/rendering.rb:30:in `process'  actionpack (5.0.0.1) lib/action_controller/metal.rb:190:in `dispatch'  actionpack (5.0.0.1) lib/action_controller/metal.rb:262:in `dispatch'  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:50:in `dispatch'  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:32:in `serve'  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve'  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `each'  actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `serve'  actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  bullet (5.4.2) lib/bullet/rack.rb:10:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/rack/agent_hooks.rb:30:in `traced_call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/rack/browser_monitoring.rb:32:in `traced_call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/rack/developer_mode.rb:48:in `traced_call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  rack (2.0.1) lib/rack/etag.rb:25:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  rack (2.0.1) lib/rack/conditional_get.rb:25:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  rack (2.0.1) lib/rack/head.rb:12:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context'  rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  activerecord (5.0.0.1) lib/active_record/migration.rb:552:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'  activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'  actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  web-console (3.4.0) lib/web_console/middleware.rb:135:in `call_app'  web-console (3.4.0) lib/web_console/middleware.rb:28:in `block in call'  web-console (3.4.0) lib/web_console/middleware.rb:18:in `catch'  web-console (3.4.0) lib/web_console/middleware.rb:18:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app'  railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged'  railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  rack (2.0.1) lib/rack/method_override.rb:22:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  rack (2.0.1) lib/rack/runtime.rb:22:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  rack (2.0.1) lib/rack/sendfile.rb:111:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  railties (5.0.0.1) lib/rails/engine.rb:522:in `call'  newrelic_rpm (3.17.1.326) lib/new_relic/agent/instrumentation/middleware_tracing.rb:96:in `call'  rack (2.0.1) lib/rack/handler/webrick.rb:86:in `service'  /Users/nicoskaralis/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/webrick/httpserver.rb:140:in `service'  /Users/nicoskaralis/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/webrick/httpserver.rb:96:in `run'  /Users/nicoskaralis/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/webrick/server.rb:296:in `block in start_thread'    Rendering /Users/nicoskaralis/.rvm/gems/ruby-2.3.1@connect-ads-channel-server/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout    Rendering /Users/nicoskaralis/.rvm/gems/ruby-2.3.1@connect-ads-channel-server/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb    Rendered /Users/nicoskaralis/.rvm/gems/ruby-2.3.1@connect-ads-channel-server/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (14.9ms)    Rendering /Users/nicoskaralis/.rvm/gems/ruby-2.3.1@connect-ads-channel-server/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb    Rendered /Users/nicoskaralis/.rvm/gems/ruby-2.3.1@connect-ads-channel-server/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (4.7ms)    Rendering /Users/nicoskaralis/.rvm/gems/ruby-2.3.1@connect-ads-channel-server/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb    Rendered /Users/nicoskaralis/.rvm/gems/ruby-2.3.1@connect-ads-channel-server/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (11.5ms)    Rendered /Users/nicoskaralis/.rvm/gems/ruby-2.3.1@connect-ads-channel-server/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (110.8ms)  

Not getting the exact output when testing Create action in RSpec

Posted: 18 Nov 2016 03:59 AM PST

I am doing my testing with mocks and stubs but I can't get the desired output I want when testing the create action in the controller.

The failing test:

describe 'authenticated user' do    let(:user) { instance_double(User) }    before do      allow(controller).to receive(:current_user) { user }      allow(controller).to receive(:authenticate_user!) { true }    end      describe "POST create" do      let(:achievement_params) { { title: "title" } }      let(:create_achievement) { instance_double(CreateAchievement) }        before do        allow(CreateAchievement).to receive(:new) { create_achievement }      end        it 'sends create message to CreateAchievement' do      expect(CreateAchievement).to receive(:new).with(achievement_params, user)      expect(create_achievement).to receive(:create)      post :create, achievement: achievement_params        end    end  end  

The create action in the controller

def create    service = CreateAchievement.new(params[:achievement], current_user)    service.create    render nothing: true  end  

The error:

  1) AchievementsController authenticated user POST create sends create message to CreateAchivement   Failure/Error: expect(CreateAchievement).to receive(:new).with(achievement_params, user)       #<CreateAchievement (class)> received :new with unexpected arguments       expected: ({:title=>"title"}, #<InstanceDouble(User) (anonymous)>)            got: (<ActionController::Parameters {"title"=>"title"} permitted: false>, #<InstanceDouble(User) (anonymous)>)     Diff:     @@ -1,2 +1,3 @@     -[{:title=>"title"}, #<InstanceDouble(User) (anonymous)>]     +[<ActionController::Parameters {"title"=>"title"} permitted: false>,     + #<InstanceDouble(User) (anonymous)>]  

Acts-as-taggable-on displaying tags on the basis of most used tags

Posted: 18 Nov 2016 04:45 AM PST

How to display tags in sorted order of usage. i have this code:

<% tag_cloud Question.tag_counts, %w[s m l] do |tag, css_class| %>  

how to make amends to display it in sorted order of usage.

unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) - Rspec

Posted: 18 Nov 2016 04:06 AM PST

Note: selenium-webdriver (2.24.0), Mozilla Firefox 45.0.2, rails (3.2.19), ruby (1.8.7)

customer_request.rb

  before(:each) do       @srtuser = login_as(:customer)    end      after(:each) do      end      def login_as(role)      u = User.where(:email => "testing@test.net").first      visit new_user_session_path      fill_in "user[email]", :with => u.email      fill_in "user[password]", :with => "changeme"      click_button "Sign in"      page.should have_content("#{u.visible_name}")      u    end  

ERROR: Failure/Error: visit new_user_session_path Selenium::WebDriver::Error::WebDriverError: unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) # ./spec/requests/customer_spec.rb:37:in `login_as' # ./spec/requests/customer_spec.rb:28

i tried downgrade and upgrade firefox didnt get any success

HTTP2 requests through PROXY, ruby

Posted: 18 Nov 2016 03:06 AM PST

I have some remote REST API running through HTTP2. It runs through SSL using certificate. The goal is to send and receive data via HTTP2 with SSL certificate via Proxy.

There are http-2 & net-http2 gems that allow to send requests with HTTP2. But what about proxy? In a standard Net::HTTP library, there is a child class, Net::HTTP::Proxy that duplicates behavior of parent's Net::HTTP class except the fact it sends requests via proxy-server. But HTTP2 gems does not support it.

The closes idea I came up is to make something similar to Proxy implementation of http1.1 - to write "Host:" and "Proxy-Authorization: " fields to the socket, that Net-Http2 gem uses:

  @socket.writeline sprintf('CONNECT %s:%s HTTP/%s',                              @address, @port, HTTPVersion)    @socket.writeline "Host: #{@address}:#{@port}"    if proxy_user      credential = ["#{proxy_user}:#{proxy_pass}"].pack('m')      credential.delete!("\r\n")      @socket.writeline "Proxy-Authorization: Basic #{credential}"    end    @socket.writeline ''  

But it ends up with:

SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A  

I might miss some technical knowledge to achieve this, so any help related to direction of research is appreciated.

AngularJS materials, Ruby on rails, $mdDialog

Posted: 18 Nov 2016 02:49 AM PST

I have a question. How to display on a pop-up window the information from the previous window. I have this code. It is my main html page

<body ng-app = "smartDeals" ng-controller = "smartDealsController as controller" >  <div class = "text">        <md-card md-theme="{{ 'dark-grey'}}">  <h1>Pizza Exemple</h1>  </md-card>      <div class='md-padding' layout="row" layout-wrap>          <md-card md-theme="{{ 'dark-grey'}}" style="width: 350px;" ng-repeat="pizza in controller.pizzas">                  <%= image_tag('6.jpg', style: "height: 250px; width: 350px") %>              <md-card-content>              <h2>{{pizza.name}}</h2>              <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>            </md-card-content>            <div class="md-actions" layout="row" layout-align="end center">                      <md-button class="md-primary md-raised" ng-click="showAdvanced($event)" flex="100" flex-gt-md="auto">           Buy       </md-button>            </div>            </md-card>        </div>  </div>          <%=yield%>    </body>  

It is my controller

(function(){  var app = angular.module('smartDeals', ['ngMaterial','ngMessages']);    app.config(function($mdThemingProvider) {    $mdThemingProvider.theme('dark-grey').backgroundPalette('grey').dark();    $mdThemingProvider.theme('dark-orange').backgroundPalette('orange').dark();    $mdThemingProvider.theme('dark-purple').backgroundPalette('deep-purple').dark();    $mdThemingProvider.theme('dark-blue').backgroundPalette('blue').dark();  });  app.controller('smartDealsController',function($scope,$mdDialog,$mdMedia){    var web3 = new Web3();    this.pizzas = pizzas;      $scope.showAdvanced = function(ev) {        $mdDialog.show({          controller: function DialogController($scope, $mdDialog) {      $scope.hide = function() {        $mdDialog.hide();      };        $scope.cancel = function() {        $mdDialog.cancel();      };        $scope.answer = function(answer) {        $mdDialog.hide(answer);      };    },          templateUrl: 'solution_controller/index',          parent: angular.element(document.body),          targetEvent: ev,          clickOutsideToClose:true,          fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.        })        .then(function(answer) {          $scope.status = 'You said the information was "' + answer + '".';        }, function() {          $scope.status = 'You cancelled the dialog.';        });      };        });      var pizzas = [        {          name: 'Vegetariana',          price: 400,          description: 'Very good pizza!',          images: [            "assets/images/1.png",            "assets/images/1.png",            "assets/images/1.png"          ],        },        {          name: 'Quattro Formaggi',          price: 300,          description: 'Very good pizza!',          images: [            "assets/images/1.png",            "assets/images/1.png",            "assets/images/1.png"          ],        },        {          name: 'Maltija (Maltese)',          price: 300,          description: 'Very good pizza!',          images: [            "assets/images/1.jpg",            "assets/images/1.jpg",            "assets/images/1.jpg"          ],        }      ];  })();  

And pop-up window

<md-dialog ng-app = "smartDeals" ng-controller = "smartDealsController as controller" >    <form>      <md-dialog-content>        <div class="md-dialog-content">          <h2>{{pizza.name}}</h2>      </md-dialog-content>        <md-dialog-actions layout="row">        <span flex></span>        <md-button ng-click="hide()">Hide</md-button>      </md-dialog-actions>    </form>  </md-dialog>  

I want to display on a pop-up window the information of only one pizza, to which the user clicked. I think I need some way to save the variable, which after clicking on the button will be pizza index entry of an array. But I do not know how to implement it. Thank you for any help

Rails nested resource - setting param: issue

Posted: 18 Nov 2016 03:47 AM PST

I have the following routes declared:

  resources :accounts, param: :account_id do       resources :instructions, param: :instruction_id  do         resources :messages, param: :message_id       end    end  

So accounts, instructions, messages are the 3 models I have. This gives me the routes:

    account_instruction_messages GET    /accounts/:account_account_id/instructions/:instruction_instruction_id/messages(.:format)                  messages#index                                   POST   /accounts/:account_account_id/instructions/:instruction_instruction_id/messages(.:format)                  messages#create   new_account_instruction_message GET    /accounts/:account_account_id/instructions/:instruction_instruction_id/messages/new(.:format)              messages#new  edit_account_instruction_message GET    /accounts/:account_account_id/instructions/:instruction_instruction_id/messages/:message_id/edit(.:format) messages#edit       account_instruction_message GET    /accounts/:account_account_id/instructions/:instruction_instruction_id/messages/:message_id(.:format)      messages#show                                   PATCH  /accounts/:account_account_id/instructions/:instruction_instruction_id/messages/:message_id(.:format)      messages#update                                   PUT    /accounts/:account_account_id/instructions/:instruction_instruction_id/messages/:message_id(.:format)      messages#update                                   DELETE /accounts/:account_account_id/instructions/:instruction_instruction_id/messages/:message_id(.:format)      messages#destroy              account_instructions GET    /accounts/:account_account_id/instructions(.:format)                                                       instructions#index                                   POST   /accounts/:account_account_id/instructions(.:format)                                                       instructions#create           new_account_instruction GET    /accounts/:account_account_id/instructions/new(.:format)                                                   instructions#new          edit_account_instruction GET    /accounts/:account_account_id/instructions/:instruction_id/edit(.:format)                                  instructions#edit               account_instruction GET    /accounts/:account_account_id/instructions/:instruction_id(.:format)                                       instructions#show                                   PATCH  /accounts/:account_account_id/instructions/:instruction_id(.:format)                                       instructions#update                                   PUT    /accounts/:account_account_id/instructions/:instruction_id(.:format)                                       instructions#update                                   DELETE /accounts/:account_account_id/instructions/:instruction_id(.:format)                                       instructions#destroy  

That looks wrong to me, I was expecting

/accounts/:account_id/instructions/:instruction_id etc...?

Can someone advise what I am doing wrong?

how to save data into has_many_through table while saving parent object with nested_form rails

Posted: 18 Nov 2016 05:38 AM PST

i have job model, skill model and job_skill model

class Job < ActiveRecord::Base        has_many :job_skills        has_many :skills ,through: :job_skills        accepts_nested_attributes_for :job_skills      class Skill < ActiveRecord::Base      has_many :job_skills      has_many :jobs ,through: :job_skills      accepts_nested_attributes_for :job_skills      class JobSkill < ActiveRecord::Base       belongs_to :skill       belongs_to :job       accepts_nested_attributes_for :job       accepts_nested_attributes_for :skill  

And jobs controller

class JobsController < ApplicationController      def new         @job = Job.new         @job.job_skills.build      end        def create        @job = Job.new(job_params)        @job.save      end      private     def job_params      params.require(:job).permit(:occupation, :industry, :location,job_skills_attributes:[])     end  

and job form is

= form_for @job do |f|     = f.label :location     = f.text_field :location        .clear       = f.label "industry*"     = f.text_field :industry   .clear       = f.label :occupation     = f.text_field :occupation   .clear     = f.label "Skill Required*"     = f.fields_for(:job_skills) do |s|      = s.select :skill_id, Skill.all.collect{|p| [p.skill, p.id]},{}, {:multiple => true, :class=> "chosen-select multiple-select-skills"}  = f.submit "submit"  

only job get save. jobs_skills doesnt save. in job params i get only jobs data. what could be the reason. please help.!!

Fetch and save the key on S3 upload with refile gem, Ruby on Rails

Posted: 18 Nov 2016 04:39 AM PST

Hi I am trying to upload images directly to S3 using refile gem

project.rb looks like

class Project < ActiveRecord::Base      has_many :photos, :class_name => "Project::Photo", dependent: :destroy      accepts_attachments_for :photos  end  

project/photo.rb

class Project::Photo < ActiveRecord::Base      belongs_to :project        attachment :file        attr_accessible :name, :address, :created_at, :project_id, :file      before_create :debugging_create      end  

config/initializers/refile.rb

require "refile/s3"    aws = {    access_key_id: "xyz",    secret_access_key: "abc",    region: "sa-east-1",    bucket: "my-bucket",  }  Refile.cache = Refile::S3.new(prefix: "cache", **aws)  Refile.store = Refile::S3.new(prefix: "store", **aws)  

Output from Refile.backends [Image 1]

enter image description here

Params on file upload looks like this for photos_files [Image 2]

enter image description here

Issues:

  1. Unable to fetch and save the key in database which is being saved into amazon S3. Different keys is shown in the Refile.backends.
  2. How to save a new file on update. Currently it overrides the existing file.

How to get data from Postman in Rails Controller?

Posted: 18 Nov 2016 05:21 AM PST

i want to ask about param post from postman so i can get it in controller in rails.

here is my controller

class Api::V1::UsersController < ApplicationController    before_action :get_user, only: [:show, :fullname]    #get all user object    def index      render :json => User.all    end      # get user object with id    def show      render :json => @user    end      # get full name of user object with id    def fullname      @hasil = @user.firstname + ' ' + @user.lastname      render :json => @hasil    end      # post object into model    def create      @user = User.new(user_params)      @user.save      if @user.save          render :json => @user      else          render :json => @user.errors.full_messages      end    end      private      def user_params        params.permit(:username, :firstname, :lastname, :age)      end        def get_user        @user = User.find(params[:id])      end  end  

when i try it in postman, i got null on username, firstname, lastname, and age.

I post it like this

[    {      "username": "admin2",      "firstname": "Reza Adha",      "lastname": "Hamonangan",      "age": 23,    }  ]  

My rails server log when i try to post

Started POST "/api/v1/users" for ::1 at 2016-11-18 18:04:24 +0700    ActiveRecord::SchemaMigration Load (0.0ms)  SELECT `schema_migrations`.* FROM `schema_migrations`  Processing by Api::V1::UsersController#create as */*      (0.0ms)  BEGIN    SQL (1.0ms)  INSERT INTO `users` (`created_at`, `updated_at`) VALUES ('2016-11-18 11:04:25', '2016-11-18 11:04:25')     (4.2ms)  COMMIT     (0.0ms)  BEGIN     (0.0ms)  COMMIT  Completed 200 OK in 22ms (Views: 0.3ms | ActiveRecord: 7.2ms)  

I think i did something wrong in my controller to get POST DATA from postman. Please help me.. Thank you for your attention.

ActionView::Template::Error (Permission denied @ utime_internal) when running Rails application in Redhat

Posted: 18 Nov 2016 02:17 AM PST

I am trying to run my Rails 4.2.6 application in Rehat 7.2 machine. I did bundle, rake db:create, migrate, seed and etc; When I start the Apache and run, I am getting error page "Something went wrong" and when I check in /var/log/httpd/error_log, this is the error I am getting:

App 4606 stderr: App 4606 stderr: Started GET "/" for 103.253.32.2 at 2016-11-18 05:10:29 -0500 App 4606 stderr: Processing by HomeController#index as HTML App 4606 stderr: Rendered home/index.html.erb within layouts/public (0.0ms) App 4606 stderr: Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.0ms) App 4606 stderr: App 4606 stderr: ActionView::Template::Error (Permission denied @ utime_internal - /var/www/html/project/MyProject/tmp/cache/assets/sprockets/v3.0/wO/wOxBFVR5aohCWkg-3a6DscZd1VRPgoEEU208_2jurtU.cache): App 4606 stderr:
5: App 4606 stderr:
6: <%= Rails.application.config.custom.app_name %> App 4606 stderr:
7: <%#= stylesheet_link_tag "marketing" %> App 4606 stderr:
8: <%= javascript_include_tag "application" %> App 4606 stderr: 9: App 4606 stderr:
10:
App 4606 stderr:

11: App 4606 stderr: app/views/layouts/public.html.erb:8:in `_app_views_layouts_public_html_erb__3726206115560412875_35861780' App 4606 stderr: App 4606 stderr: ~

Please help.

Assigns method returns nil in RSpec

Posted: 18 Nov 2016 02:00 AM PST

I am doing my testing with mocks and stubs but I keep getting nil in my output. I am not sure if it's the problem with the assigns method. Could I also know how I should debug this kind of problem? I am using rspec-rails 3.5.2 Thank you.

The failing test:

describe 'guest user' do     describe 'GET index' do       let(:achievement) { instance_double(Achievement) }         before do         allow(Achievement).to receive(:get_public_achievements) { [achievement] }       end         it 'assigns public achievements to template' do         get :index         expect(assigns(achievement)).to eq([achievement])       end     end  end  

The index action in the controller

 def index     @achievements = Achievement.get_public_achievements   end  

The get_public_achievements in the achievement model

  def self.get_public_achievements       // empty method it's fine    end  

The error:

1) AchievementsController guest user GET index assigns public achievements to template   Failure/Error: expect(assigns(achievement)).to eq([achievement])       expected: [#<InstanceDouble(Achievement) (anonymous)>]          got: nil       (compared using ==)  

get date without offset

Posted: 18 Nov 2016 03:09 AM PST

I'm using MySQL to store my data. I'm recorded dates with different offset according to each timezone. What is important on those dates are only "effective" time. Here is an example:

date1 = "Thu, 27 Oct 2016 07:00:00 CEST +02:00"  # I want to get 700  date2 = "Thu, 27 Oct 2016 22:00:00 CEST +02:00"  # I want to get 2200  

I would like to get these values to compare them with my current time. Then if it's currently "2016-11-17 10:12:00 +0100", I would like to compare on a where clause : "1012" > "2200" # or "1012" > "700"

Here is a fake record value:

# my_table  # | id | my_hour  # | XX | "Thu, 27 Oct 2016 07:00:00 CEST +02:00"  # | XY | "Thu, 27 Oct 2016 22:00:00 CEST +11:00"  

Here is my code:

hour = Time.zone.now  # "2016-11-18 21:10:00 +0100"  where("CAST(DATE_FORMAT(my_hour,'%H%i') AS UNSIGNED) < ?", hour.strftime("%H%M").to_i)  # => Get XX record?  

Thanks for your help.

No comments:

Post a Comment