Thursday, March 31, 2016

How to find a randomic ID on HTML page (Cucumber/Capybara) | Fixed issues

How to find a randomic ID on HTML page (Cucumber/Capybara) | Fixed issues


How to find a randomic ID on HTML page (Cucumber/Capybara)

Posted: 31 Mar 2016 07:10 AM PDT

I'm trying to test an application that generate tickets, so I have to open a ticket and then assume it. I'm having a problem with the part of assume it, because the tickets are opened with a random ID (the number of the ticket).

<button type="submit" id="assign_ticket_6168218" class="btn btn-primary exchange_button">  <i class="fa fa-thumbs-up"></i> Assume  

The number of id="assign_ticket_6168218" is random, but the other part is always the same. So, I'm creating the ticket and now I have to click on the button to assume it. How can I create a ticket and store the number of the ticket to use it on the ID?

PS: If this is importante, when a create the ticket, I receive a confirmation message with the ticket's ID:

`<div id="messages" class="clearfix">    <div class="success global alert-default form-section">     <ul>        <li><i class="fa fa-check"></i>Ticket 6168218 created.</li>    </ul>      <a href="javascript:;" class="close-alert"><strong>x</strong></a>   </div>  

`

Attribute translations for multiple Active Record models

Posted: 31 Mar 2016 07:07 AM PDT

I have several related-yet-distinct AR models that contain attributes representing the same piece of data. When I set up translations for these attributes, I'm currently setting them up as...

en:    activerecord:      attributes:        model_a:          assigned_date: "Assigned to worker"        model_b:          assigned_date: "Assigned to worker"        [ ... ]  

Is there any way to define this translation once, in some kind of wildcard fashion?

The approach I thought made the most sense...

en:    activerecord:      attributes:        assigned_date: "Assigned to worker"        model_a:          [ model-specific translations here ]  

Doesn't work because AR is obviously looking for a model name at the tier beneath attributes

Nested forms creates empty instances

Posted: 31 Mar 2016 07:02 AM PDT

I have a Post and a MaterielLink models. A post has_many materiel_links, and accepts_nested_attributes_for :materiel_links

I use the gem cocoon to create a nested form: on the post form, I want to be able to add links that will be created on submit of the form.

post/new.html.erb:

<%= simple_form_for @post, :html => { :id => "post_form", "data-post-id" => @post.id } do |f| %>    <%= f.simple_fields_for :materiel_links do |materiel_link| %>      <%= render 'materiel_link_fields', f: materiel_link %>    <% end %>      <%= link_to_add_association 'Ajouter', f, :materiel_links%>   <% end %>  

_materiel_link_fields.html.erb:

<%= f.fields_for :materiel_links do |materiel_link| %>    <%= materiel_link.text_field :name %>    <%= materiel_link.text_field :link %>  <% end %>  

In my post controller:

 def update      @materiel_links = @post.materiel_links.build(post_params[:materiel_links_attributes]        if @post.update!(post_params)        session[:current_draft_post_id] = nil        redirect_to post_path(@post)      else        render :new      end    end  

And the params:

def post_params      params.require(:post).permit(:title, materiel_links_attributes: [:name,:link] )  end  

I added a raise in the update action, and what is stange is that I can find the link/name for each materiel_link I've added when I type params but with a number before each couple:

>> params  {"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"wqzWfaAcwrOOdxViYBO5HaV2bwsNsf5HsvDFEbBYapkOMAPXOJR7oT4zQHbc/hTW8T9a+iH5NRl1WUApxrIjkA==", "post"=>{"title"=>"my title", "materiel_links_attributes"=>{"1459431927732"=>{"materiel_links"=>{"name"=>"mon Lien 1", "link"=>"htttp1"}}, "1459431933881"=>{"materiel_links"=>{"name"=>" Mon lien 2", "link"=>"htttp2"}}}}, "controller"=>"posts", "action"=>"update", "id"=>"1250"}  

But nothing in the materiel_links hashes when I type post_params:

>> post_params  => {"title"=>"my title","materiel_links_attributes"=>{"1459431927732"=>{}, "1459431933881"=>{}}}  

The instances of MaterielLink are created, but they are empty: they don't save the link/name.

Where did I go wrong ?

Rails, abilities with cancancan

Posted: 31 Mar 2016 06:53 AM PDT

I am using cancancan to define abilities for my demo restaurant app. Each restaurant has_many employees and each employee has user_id and role attributes. I would like to allow a user to edit a restaurant only if this restaurant has an employee with user_id as the current_user.id and his role is 'manager'. My problem is that this role could be given to a lot of employees and when I find them by

can :edit, Restaurant do |restaurant|      restaurant.employees.where(role: 'Manager').id=user.id   end  

I would get an array of all managers and this code would not return true. Any ideas of how to implement this :? Thanks!

Post wordpress search result to Ruby on rails application

Posted: 31 Mar 2016 06:37 AM PDT

I am not a developer, i just install, optimize and maintain wordpress sites. So we've got a client who wants to have a site where the front end is powered by wordpress and the backend is powered by ruby on rails.

I've finished building the front end site with wordpress and our developers did their jobs in ROR.

Now my problem is i have a search box on the home page where a user inputs his address and the address gets validated by smartystreets.

All i have to do now is post the validated info to a registration form in the ruby on rails app.

Below is the code of wordpress search form.

<form method="post" action=""><input type="text" name="street" placeholder="<?php echo esc_attr($placeholder);?>" class="search"  value="<?php echo the_search_query(); ?>"/>  <input type="submit" id="searchsubmit" value="">  </form>  

Guys please help me out

Rails Inadvertantly Showing JSON in View

Posted: 31 Mar 2016 06:29 AM PDT

I'm using Rails 4 and have a weird issue in one of my views. In my controller I'm getting a weather feed from OpenWeatherMap.org using the Ruby_Open_Weather_Map gem. The data is returned as JSON and I am looping through the JSON and extracting the forcast information for the next 5 days. What's weird is that after my loop, the JSON data is displayed.

enter image description here

I'm new to Rails and to JSON and this doesn't make any sense to me. I have a second page that has even more information on it and the same thing happens. This is what my controller looks like:

  def index      options = { units: "Imperial", APPID: '6eff99d4b460d3a1acddcf1a727a7a45' }      @currentweather = OpenWeather::Current.city("Greenville, SC", options)      @forcastweather = OpenWeather::ForecastDaily.city("Greenville, SC", options)    end  

and this is what my view looks like:

    <%= @forcastweather['list'].each do | day | %>      <div class ="row">        <div class="col-xs-5">          <strong><%= Time.at(DateTime.strptime(day['dt'].to_s,'%s')).in_time_zone("Eastern Time (US & Canada)").strftime("%A") %></strong>        </div>        <div class="col-xs-3">          <%= day['temp']['min'] %>        </div>        <div class="col-xs-3">          <%= day['temp']['max'] %>        </div>        <div class="col-xs-2">          <img src="http://openweathermap.org/img/w/<%= day['weather'][0]['icon'] %>.png" alt="<%= day['weather'][0]['main'].humanize %>">        </div>      </div>    <% end %>  

Why is the JSON displaying in my view and how do I fix it? Thanks for your help with this.

rubywmq: Failed to load MQ Library:libmqic_r.so,

Posted: 31 Mar 2016 07:01 AM PDT

From a rails 4.1.5 application I'm trying to connect to a remote IBM Websphere MQ Server. I've successfully installed the rubywmq gem. By following the instruction the Development Toolkit (SDK) and MQ Client are successfully installed on local machine(Ubuntu OS).

To test the installation I added a rake task with following code:

require 'wmq'    desc 'Connect to Volvo'    task :volvo => :environment do    WMQ::QueueManager.connect(connection_name: 'n.n.n.n(1417)')  do |qmgr|      puts qmgr      end  end  

I got the following error:

rake aborted!  WMQ::WMQException: WMQ::QueueManager#connect(). Failed to load MQ Library:libmqic_r.so, rc=libmqe_r.so: cannot open shared object file: No such file or directory  /home/arifmuhammad/code/wheresmyconcrete/lib/tasks/volvo_integration.rake:6:in `connect'  /home/arifmuhammad/code/wheresmyconcrete/lib/tasks/volvo_integration.rake:6:in `block in <top (required)>'  /home/arifmuhammad/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `eval'  /home/arifmuhammad/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `<main>'  Tasks: TOP => volvo  (See full trace by running task with --trace)  

Although the file libmqic_r.so exists in /opt/mqm/lib

I did some workaround but couldn't find the solution. Am I missing something in configuration, any clue?

How to combine two activerecord queries?

Posted: 31 Mar 2016 06:23 AM PDT

Lets say we have Event model, and SearchEngine class which performs searches on events.

SearchEngine has search method.

class SearchEngine    def search(event_scope)      return Event.all if event_scope.nil?      //event_scope combined with Event.where('name = ?','test')    end  end  

I'd like to be able to pass event_scope like this:

SearchEngine.new.search(Event.where('start_time > ?',Time.now))  

And the result would be the same as:

Event.where('start_time > ?',Time.now).where('name = ?','test')  

How can I do this?

Rails diaspora XMPP chat

Posted: 31 Mar 2016 05:57 AM PDT

I have a diaspora pod. The issues is, when I enabled the chat and run the command ./script/server, my chat system returning an error as follow:

http://localhost:3000/http-bind 404 (Not Found)

Following were my diaspora.yml config:

server: ## Section          # Start built-in XMPP server (default=true).        # In case you want to run your own server, you should disable it.        enabled: false          # Set the directory in which to look for virtual hosts TLS certificates.        # Check documentation on how to generate or configure your existing        # certficates correctly:        #        # https://wiki.diasporafoundation.org/Vines#Certificates        certs: 'config/vines'          # The server accepts by default only valid certificates.        # Any connection which uses self-signed ones will be closed.        # If you'd like to accept self-signed certificates        # on your server, set the next option to true.        accept_self_signed: true          # Only edit the next option if you'd like to deny        # your users to exchange messages between other XMPP servers.        cross_domain_messages: false          # Set the maximum of offline messages stored per user (default=150).        # If it exceeds, it will start deleting old messages. You can disable        # offline message support completely by setting the option to zero.        max_offline_msgs: 150          ## Client to server        c2s: ## Section            # Configure the address that vines should listen on.          address: '0.0.0.0'            # Configure the client-to-server port.          # If your server is behind a router or firewall          # check documentation on how to forward ports:          #          # https://wiki.diasporafoundation.org/Vines#Firewall_Ports          port: 5222            # The maximum we'd like to allow for stanza size.          max_stanza_size: 65536            # The max_resources_per_account attribute, limits how many          # concurrent connections one user can have to the server.          max_resources_per_account: 5          ## Server to server        s2s: ## Section            # Configure the address that vines should listen on.          address: '0.0.0.0'            # Configure the server-to-server port.          # If your server is behind a router or firewall          # check documentation on how to forward ports:          #          # https://wiki.diasporafoundation.org/Vines#Firewall_Ports          port: 5269            # The max_stanza_size attribute should be          # much larger than the setting for client-to-server.          max_stanza_size: 131072            # By default every XMPP server with a valid certificate          # is able to communicate with your server. In case of a          # malicious server (e.g. spam reason), you can black-list them.          blacklist:           - 'example.com'           - 'malicous.net'          ## XEP-0124 BOSH requests        bosh: ## Section            # If you'd like to use a proxy, you should set the proxy          # option to true, otherwise jsxc always tries to          # connect directly to the port specified below.          proxy: true            # Configure the address that vines should listen on.          address: '0.0.0.0'            # Configure the BOSH port.          port: 5280            # Configure the bind endpoint.          bind: '/http-bind'            # The maximum we'd like to allow for stanza size.          max_stanza_size: 65536            # The max_resources_per_account attribute, limits how many          # concurrent connections one user can have to the server.          max_resources_per_account: 5  

How do I setup XMPP chat server for my diaspora pod?

Render email in stead of user_id but with 2 custom ids on the record - Ruby On Rails

Posted: 31 Mar 2016 06:13 AM PDT

Im a bit new to Ruby on Rails so I'm hoping this isn't a stupid question.

I'm trying to make an application to store played fifa games.

This requires 2 users linked to one game, but offcourse one user can also have many games, therefore I used a many-to-many relation.

Controller:

class GamesController < ApplicationController          before_action :authenticate_user!, exept: [:index, :show]        def index          @games = Game.all          end        def new          @game = current_user.games.build          @user_options = User.all.map{|u| [ u.email, u.id ] }      end        def create          @user_options = User.all.map{|u| [ u.email, u.id ] }          @game = Game.new(game_params)            @game.home_team_user_id = current_user.id          @game.home_team_user_name = current_user.email                       if @game.save              redirect_to games_path, :notice => "Successfully added game!"          else              render 'index'          end      end        def show          @games = Game.all      end        def destroy          @game = Game.find(params[:id])          @game.destroy          redirect_to games_path      end          private      def find_game              @game = Game.find(params[:id])          end        def game_params          params.require(:game).permit(:home_team_user_name, :home_score, :away_team_user_name, :away_score, :home_team_user_id, :away_team_user_id)      end  end  

View File:

  <div class="panel panel-default" style="margin-left: 10px; margin-right:10px">    <!-- Default panel contents -->    <div class="panel-heading">Played games</div>      <!-- Table -->            <table class="table">               <thead>                   <th>Home Team</th>                   <th>Home Team Score</th>                   <th>Away Team Score</th>                   <th>Away Team</th>                   <th>Added by</th>                   <th>Actions</th>                </thead>                  <% @games.each do |game|%>                    <tbody>                   <td>                    <%= game.home_team_user_id %>                  </td>                  <td>                    <%= game.home_score %>                </td>                <td>                    <%= game.away_score %>                </td>                <td>                    <%= game.away_team_user_id %>                </td>                    <td>                    </td>                <td>                    <%= link_to "Delete", game, method: :delete, data: { confrim: "Are you sure?"} %>                  </td>                       <% end %>                </tbody>            </table>            </div>  

New Game form:

    <div class="col-md-12" style="text-align:center">          <div class="panel panel-default" style="margin-right:10px">              <div class="panel-heading">                  <h3 class="panel-title">Submit New Match</h3>              </div>              <div class="panel-body">                    <%= simple_form_for(@game) do |f| %>                  <%= f.text_field :home_score, :placeholder => "Your score" %>                  <%= f.text_field :away_score, :placeholder => "Your Opponents score" %>                     <%= f.select(:away_team_user_id, @user_options) %>                    <%= f.submit "Submit Match", class: "btn-submit" %>                  <% end %>         <!--     <%= form_for @game do |f| %>                    <%= collection_select(:game, :away_team_user_id, User.all, :id, :email, prompt: true ) %>                  <%= f.text_field :home_score, :placeholder => "Your score" %>                  <%= f.text_field :away_score, :placeholder => "Your Opponents score" %>                <%= f.submit "Submit Match", class: "btn-submit" %>            <% end %> -->        </div>  </div>  

Now I'm able to add games with the home_team_user_id = current_user away_team_user_id = user selected from dropdown menu

and offcourse the score.

However in the view the email adresses should be shown in stead of the id's.

I've tried many solutions like <%= game.home_team_user_id.user.email %>

This gives the error : undefined method `user' for 1:Fixnum

Can anybody help me on this mather? What am I doing wrong?

Thx in advance!

Image not found on Rails + Phaser

Posted: 31 Mar 2016 05:42 AM PDT

I'm trying to complete this tutorial of phaser but I can't get the images to load. I started by adding the following code to one of my views:

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {

game.load.image ('sky', 'assets/images/sky.png');  game.load.image ('ground', 'assets/images/platform.png');  game.load.image ('star', 'assets/images/star.png');  game.load.spritesheet ('dude', 'assets/images/dude.png', 32, 48);  

}

var platforms;

function create() {

game.physics.startSystem(Phaser.Physics.ARCADE);  game.add.sprite(0, 0, 'sky');  platforms = game.add.group();  platforms.enableBody = true;  var ground = platforms.create(0, game.world.height - 64, 'ground');  ground.scale.setTo(2, 2);  ground.body.immovable = true;  var ledge = platforms.create(400, 400, 'ground');  ledge.body.immovable = true;  ledge = platforms.create(-150, 250, 'ground');  ledge.body.immovable = true;  

}

The game window appears but none of the images are being displayed. When I inspect the page, I can see the following error message:

Phaser.Loader - image[sky]: error loading asset from URL assets/images/sky.png

It appears for every image I tried to load. I already checked if the path is correct, and it is. Anyone have an idea of what is happening?

db/development.sqlite3 merge conflict in Rails 4

Posted: 31 Mar 2016 05:41 AM PDT

I ran into a merge conflict in file db/development.sqlite3.

warning: Cannot merge binary files: db/development.sqlite3 (HEAD vs. nest-questions)  Auto-merging db/development.sqlite3  CONFLICT (content): Merge conflict in db/development.sqlite3  

Normally I would open file (in Cloud9 IDE), manually edit out the conflict, and done.

But I cannot read anything in this file - it just looks like gibberish.

The app is in development. Can i just wipe out the file, then run rake db:reset, or will cause issues? I've never manually modified this file before.

Has anyone resolved a conflict in db/development.sqlite3 before and can advise?

How to use find_or_create in create action?

Posted: 31 Mar 2016 05:54 AM PDT

I want to use find_or_create method in my game dates controller. I don't know how to use that method in create action, when params are in game_date_params. Any suggestion how can I extract date from game_date_params?

class GameDatesController < ApplicationController    before_action :authenticate_user!    before_action :authenticate_admin      def index      @game_dates = GameDate.all      @showcases  = Showcase.joins(:game_dates)    end      def new      @game_date = GameDate.new      @game_date.referee_stats.build    end      def create      @game_date = GameDate.new(game_date_params)      if @game_date.save        redirect_to showcases_path        flash[:success] = "Game date created"      else        render 'new'      end    end      def show      @game_date = GameDate.find(params[:id])    end      def destroy      @game_date = GameDate.find(params[:id]).destroy      redirect_to root_url      flash[:success] = "Game date deleted"    end        private      def game_date_params      params.require(:game_date).permit(:date, referee_stats_attributes: [ :games_count, :showcase_id ])    end  

Ruby: Wrong number of arguments Error when calling method with a parameter with a default value

Posted: 31 Mar 2016 06:37 AM PDT

I'm working with PageObject and DataMagic to populate a form in a page, and I use a method to set the data, that has a parameter defined with a default value. I was able to call the method without defining any parameters(page.checkout), but after a change in the code it is giving me this error:

wrong number of arguments (0 for 1) (ArgumentError)

This is my code before the change, which works fine:

class CheckoutPage    include PageObject      DEFAULT_DATA = {      'name' => Faker::Name.name,      'address' => Faker::Address.street_address,      'email' => Faker::Internet.email,      'pay_type' => 'Credit card'   }      text_field(:name, :id => "order_name")    text_field(:address, :id => "order_address")    text_field(:email, :id => "order_email")    select_list(:pay_type, :id => "order_pay_type")    button(:place_order, :value => "Place Order")      def checkout(data = {})      populate_page_with DEFAULT_DATA.merge(data)      place_order    end    end  

But when I made this change, it started giving me the error message when called without parameters (works just fine if I call page.checkout(data_hash):

class CheckoutPage    include PageObject    include DataMagic      text_field(:name, :id => "order_name")    text_field(:address, :id => "order_address")    text_field(:email, :id => "order_email")    select_list(:pay_type, :id => "order_pay_type")    button(:place_order, :value => "Place Order")      def checkout(data = {})      populate_page_with data_for(:checkout_page, data)      place_order    end    end  

I tested this to make sure it's not a problem with DataMagic, and I didn't get the Error, however, it makes no sense to my code, so it's not a possible solution:

class CheckoutPage    include PageObject    include DataMagic      DEFAULT_DATA = {      'name' => Faker::Name.name,      'address' => Faker::Address.street_address,      'email' => Faker::Internet.email,      'pay_type' => 'Credit card'   }      text_field(:name, :id => "order_name")    text_field(:address, :id => "order_address")    text_field(:email, :id => "order_email")    select_list(:pay_type, :id => "order_pay_type")    button(:place_order, :value => "Place Order")      def checkout(data = {})      populate_page_with data_for(:checkout_page, DEFAULT_DATA.merge(data))      place_order    end    end  

Shouldn't this method be creating an empty hash by default and therefore having the necessary parameters to do the action, whether I define parameters in the call or not?

I'm using Ruby 2.2.5

Rails. Is the way to access to params hash from model concern?

Posted: 31 Mar 2016 05:56 AM PDT

I need to access to params inside my concern

module UrlGenerator    extend ActiveSupport::Concern    def test      params[:slug]    end   end  

How can i do? Thanks

Rails/Rspec JSON integers being converted to strings when testing post call

Posted: 31 Mar 2016 05:24 AM PDT

I am testing a JSON request to our API, It will respond with JSON. It seems like all the integers within the JSON get converted to strings as we post them to the controller consider action.

Controller

  def consider      binding.pry # binding no# 2 used to check the params after post from test.      if ParametersValidator.is_valid?(params)        application_handler = ApplicationHandler.new(request_interactor)        render json: application_handler.result      else        render json: ParametersValidator.failed_params(params).to_json      end    end  

The ParamaterValidator validates the structure and types of data coming in.

Test

render_views  let(:json) { JSON.parse(response.body) }  ..  ..    it 'returns the result in the correct format for the AUTOMATIC APPROVE decision' do    automatic_approve_params = relative_json_file(relative_file('automatic_approve_params'))    expected_approve_params = {      "status" => "accepted",      "automated" => true,      "rate" => 6,      "amount" => 30000,      "term" => 10,      "pre_approved_amount" => 2500,      "comments" => ""    }    @request.headers['HTTP_X_AUTH_SIG'] = Rails.application.secrets['authorization']['token']    request.env["HTTP_ACCEPT"] = 'application/json'      binding.pry  # binding no# 1 to inspect the params before post      post :consider, automatic_approve_params, format: :json    expect(json).to eq(expected_approve_params)  end  

Binding no#1

{   "student_id"=>1,   "age"=>22,   "name"=>"John",   "age_range"=>"22-25",   "criminal_record"=>false,   "declared_bankrupt"=>false,   "declared_insolvent"=>false,   "declared_sequestrated"=>false,   "defaulted_on_loan"=>false,   "post_study_salary"=>100000000,   "first_nationality"=>"PL",   "second_nationality"=>"",   "citizenship"=>"PL",  }  

Binding no#2

{   "student_id"=>"1",   "age"=>"22",   "name"=>"John",   "age_range"=>"22-25",   "criminal_record"=>false,   "declared_bankrupt"=>false,   "declared_insolvent"=>false,   "declared_sequestrated"=>false,   "defaulted_on_loan"=>false,   "post_study_salary"=>"100000000",   "first_nationality"=>"PL",   "second_nationality"=>"",   "citizenship"=>"PL",  }  

The test log is showing that the request is

Processing by Api::V1::CreditApplicationsController#consider as JSON  

Inspecting the request just before the post action you will see the params are fine, then in the controller before I run anything I inspect the params and they are all strings.

Using postman to test the API with the JSON works as expected but it seems that rspec when posting to the consider action will convert all the params to strings. I have read a few dozen posts that claim by adding format: :json to the post action it will remedy this, however I have had no such luck.

I am obviously doing something wrong but I have tried pretty much everything I know.

Spree multi tenant

Posted: 31 Mar 2016 05:17 AM PDT

i am using gem 'spree_multi_tenant' to achieve multi tenant support to spree https://github.com/stefansenk/spree_multi_tenant

i have created a tenant as per documentation at my local system using command

bundle exec rake spree_multi_tenant:create_tenant_and_assign domain=mydomain.com code=mydomain  

now i am unable to load access this domain at my local system. any one has idea how can i run it?

Setting Paperclip attachments with Asset Pipeline

Posted: 31 Mar 2016 04:51 AM PDT

in my users_controller.rb I'm trying to set the profile picture of a user based on a the school that they were identified with through Paperclip.

I have the complete paperclip model setup, and it works with uploading images, but now I am removing the upload images feature in exchange for set images in the asset pipeline under /app/assets/images.

How should I set the images? I'm hoping for something to work like this:

if current_user.school == "SCHOOL1"      current_user.avatar = "SCHOOL1.png"  

I tried to make this work by replacing the "SCHOOL1.png" part above with ActionController::Base.helpers.asset_path('SCHOOL1.png') but that isn't working.

Please help!~

Rails 4 ActionMailer : is it possible to check the current mail recipient in the mailer view

Posted: 31 Mar 2016 05:08 AM PDT

I am sending a mail with bcc: option, and I would like to include a conditional inside the mailer view based on it. Something like

<% unless current_recipient is bcc email %>      text/links to display   <% end %>  

Is it possible to check the current recipient value when you have many in the to: or bcc: mail method options ?

Thanks

rails4 after caching query still runs

Posted: 31 Mar 2016 06:27 AM PDT

I have a rails 4 app and trying to implement caching. I use the @profiles_sidebar.first cache key for checking if new user was created. I'm not sure if this is ok, since there still is a db query. Is this the preferred mechanism to check if caching needs to be expired? Am I doing well?

<% cache(@profiles_sidebar.first) do %>    <% @profiles_sidebar.each do |profile| %>      <%= link_to user_path(profile.user) do %>                    <%= truncate(profile.full_name, length: 25) %>        <%= truncate(profile.company, length:25) %>      <% end %>    <% end %>  <% end %>  

console code when reading cache:

13:31:53 puma.1    |   Profile Load (2.2ms)  SELECT  "profiles".* FROM "profiles"  ORDER BY "profiles"."created_at" DESC LIMIT 1  13:31:53 puma.1    |   User Load (2.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" IN (67)  13:31:53 puma.1    |   Cache digest for app/views/users/_user_sidebar.html.erb: bfc9447057c94bcfe13c18e391127f2d  13:31:53 puma.1    | Read fragment views/profiles/62-20160331112332689423000/bfc9447057c94bcfe13c18e391127f2d (0.2ms)  13:31:53 puma.1    |   Rendered users/_user_sidebar.html.erb (11.8ms)  

Correct way to store a business's open hours, when they're open til past midnight

Posted: 31 Mar 2016 06:14 AM PDT

My app have several stores. Some stores are open from say 12PM til 04AM the following day.

The issue with our current code is that we store open time and close time. Now that means for the first day you can put 12PM - 11:59PM but the next day it's still open for another 4 hours, before it again opens up at 12PM and technically closes at 1 minute before midnight.

Does anybody have any experience with this issue, and how did you go about solving this and setting it up in the DB?

Save each JSON object to a model

Posted: 31 Mar 2016 07:04 AM PDT

I'm looking to save each JSON object within the call to a model so I don't have to call the API every single time I load up the application, instead I call all the models entries.

require 'httparty'  require 'json'    class Feed < ActiveRecord::Base    include HTTParty    base_uri 'https://www.parsehub.com/api/v2/projects'      # GET /feeds    # GET /feeds.json    def boom      response = self.class.get("/tVv8nTahbhgkyIUW8ByCe0-7/last_ready_run/data?&format=json")      @elements = response.parsed_response["image"]      @parsed = @elements.collect { |e| e['url'] }    end  

This is what I currently have within my model, which perfectly calls the API and displays each one of them within my view. Obviously this isn't the greatest way of doing this, I would like to save each of the JSON's URL property to my model - not entirely sure how to go about doing this!

Rails with Existing Database Model has no columns

Posted: 31 Mar 2016 04:49 AM PDT

Im developing a new rails app with an existing SQL SERVER 2008 database.

I read somewhere that rails 4.2 doesn't support SQL SERVER 2008 so I downgraded to 4.1 (if this matters)

I create a model using rails g model command then deleted the migration file

class IpProject < ActiveRecord::Base      self.table_name = 'IP_Projects'      self.primary_key = "ProjectID"  end  

when I try to query

IpProject.all.count  

it shows the number of rows

but I can't display the output I then tried to display the columns by

IpProject.column_names  

but it's an empty []

Could someone tell me what I'm missing here?

By the way I'm using tiny_tds and activerecord-sqlserver-adapter

ruby on rails asset pipeline not compiling colour variables

Posted: 31 Mar 2016 04:19 AM PDT

hi i am using google MDL and have noticed that the scss doesn't seem to be compiling the colour variables. all other variables are being compiled

see below $color-primary etc..

.mdl-layout__header {    display: flex;    flex-direction: column;    flex-wrap: nowrap;    justify-content: flex-start;    box-sizing: border-box;    flex-shrink: 0;    width: 100%;    margin: 0;    padding: 0;    border: none;    min-height: 64px;    max-height: 1000px;    z-index: 3;    background-color: rgb($color-primary);    color: rgb($color-primary-contrast);  

Get files which has been modified from Git API using comparison URL

Posted: 31 Mar 2016 03:59 AM PDT

I need the files which has been modified in the comparison of two branches. Here is an example: https://api.github.com/repos/git/git/compare/v2.2.0-rc1...v2.2.0-rc2

If we scroll down to the files we have this:

"files": [      {        "sha": "d4001c5ae5e82e6955b0de8b4d762c56d3bc3cdc",        "filename": "Documentation/RelNotes/2.2.0.txt",        "status": "modified",        "additions": 14,        "deletions": 0,        "changes": 14,        "blob_url": "https://github.com/git/git/blob/49e0c5ad0ab95e450138105ff27688861a4a1557/Documentation/RelNotes/2.2.0.txt",        "raw_url": "https://github.com/git/git/raw/49e0c5ad0ab95e450138105ff27688861a4a1557/Documentation/RelNotes/2.2.0.txt",        "contents_url": "https://api.github.com/repos/git/git/contents/Documentation/RelNotes/2.2.0.txt?ref=49e0c5ad0ab95e450138105ff27688861a4a1557",        "patch": "@@ -295,3 +295,17 @@ notes for details).\n    object reachability bitmap when it needs to split the resulting\n    pack.\n    (merge 2113471 jk/pack-objects-no-bitmap-when-splitting later to maint).\n+\n+ * The code to use cache-tree trusted the on-disk data too much and\n+   fell into an infinite loop upon seeing an incorrectly recorded\n+   index file.\n+   (merge 729dbbd jk/cache-tree-protect-from-broken-libgit2 later to maint).\n+\n+ * \"git fetch\" into a repository where branch B was deleted earlier\n+   back when it had reflog enabled, and then branch B/C is fetched\n+   into it without reflog enabled, which is arguably an unlikely\n+   corner case, unnecessarily failed.\n+   (merge aae828b jk/fetch-reflog-df-conflict later to maint).\n+\n+ * \"git log --first-parent -L...\" used to crash.\n+   (merge a8787c5 tm/line-log-first-parent later to maint)."      },      {        "sha": "922072596fdd80eaaa47746fba5e5591223c5108",        "filename": "Documentation/config.txt",        "status": "modified",        "additions": 2,        "deletions": 2,        "changes": 4,        "blob_url": "https://github.com/git/git/blob/49e0c5ad0ab95e450138105ff27688861a4a1557/Documentation/config.txt",        "raw_url": "https://github.com/git/git/raw/49e0c5ad0ab95e450138105ff27688861a4a1557/Documentation/config.txt",        "contents_url": "https://api.github.com/repos/git/git/contents/Documentation/config.txt?ref=49e0c5ad0ab95e450138105ff27688861a4a1557",        "patch": "@@ -683,7 +683,7 @@ alias.*::\n \tconfusion and troubles with script usage, aliases that\n \thide existing Git commands are ignored. Arguments are split by\n \tspaces, the usual shell quoting and escaping is supported.\n-\tquote pair and a backslash can be used to quote them.\n+\tA quote pair or a backslash can be used to quote them.\n +\n If the alias expansion is prefixed with an exclamation point,\n it will be treated as a shell command.  For example, defining\n@@ -2339,7 +2339,7 @@ status.showUntrackedFiles::\n \tfiles which are not currently tracked by Git. Directories which\n \tcontain only untracked files, are shown with the directory name\n \tonly. Showing untracked files means that Git needs to lstat() all\n-\tall the files in the whole repository, which might be slow on some\n+\tthe files in the whole repository, which might be slow on some\n \tsystems. So, this variable controls how the commands displays\n \tthe untracked files. Possible values are:\n +"      },  

There are two status modified and added. Now I use this command in rails to get the files changed:

url = "https://api.github.com/repos/git/git/compare/#{parent_branch}...#{current_branch}?access_token=#{token}"  files = `curl -i #{url} | grep filename | cut -f2 -d: | grep \.rb | tr '"', '\ '`  files.tr!("\n", ' ')  

This gets me all the file names but I need the file names of only those files which have status: "modified". I tried using the and in curl like this: grep 'filename.status' but it didn't work.

Sidekiq workers suddenly slowed down (almost like stuck workers)

Posted: 31 Mar 2016 03:58 AM PDT

I've been using sidekiq for a while now and it was working flawlessly (up to 5 million jobs processed). However in the past few days the workers got stuck and thus the jobs left unprocessed. Only by restarting the workers, they'll start working and consuming the jobs again, but they'll eventually stuck again (~10-30minutes, I haven't done any exact measurements).

Here's my setup:

  • Rails v4.2.5.1, with ActiveJob.
  • MySQL DB, clustered (with 3 masters)
  • ActiveRecord::Base.connection_pool set to 32 (verified in Sidekiq process as well).
  • 2 sidekiq workers, 3 threads per worker (total 6).

Symptons:

  • If the workers just got restarted, they process the jobs fast (~1s).

  • After several jobs processed, the time needed to complete a job (the same job that previously take only ~1s to complete) suddenly spiked to ~2900s, which make the worker look like stuck.

  • The slows down affect any kind of jobs (there's no specific offending job).

  • CPU usage and Memory consumption is normal and no swap either.

Here is the TTIN log. It seems like the process hung when:

  • retrieve_connection
  • clear_active_connections

But I'm not sure why it is happening. Anyone have similar experience or know something about this issue? Thanks in advance.

Access form_for object in corresponding controller method

Posted: 31 Mar 2016 04:50 AM PDT

I have a form_for, and I want to access variable of it in corresponding submit controller method. I'll explain what I mean: I have list of objects rendered as follows:

<%= render medical_situations %>

I corresponding medical_situation.html.erb file I specify how each object looks like, where inside of each I have form_for as follows:

<%= form_for medical_situation, {url: :send_to_pool_medical_situations, method: :post, remote:true} do |f| %>

In corresponding controller method I want to access that particular medical_situation object. Is it possible. I know I could pass medical_situation_id to find appropriate object but I am interested can I do it without extra request and code. In my send_to_poo method I want to do update that object.

Rails & JQuery: Invalid association. Make sure that accepts_nested_attributes_for is used for

Posted: 31 Mar 2016 04:52 AM PDT

Although I'd like to add link_to_add with using simple_nested_form_for, the following error was displayed.

ArgumentError (Invalid association. Make sure that accepts_nested_attributes_for is used for :events association.):

There are similar questions in stackoverflow, but it doesn't work for me. So I post this as a new question.

The error was appeared when I add f.link_to_add in _schedule_form.html.erb.

_schedule_form.html.erb

<%= f.label :title %>  <%= f.text_field :title, class: 'form-control' %>  <br>  <%= f.label :departure_date %>  <div class="input-group date" id="datetimepicker">    <%= f.text_field :departure_date, class: 'form-control' %>    <span class="input-group-addon">      <span class="glyphicon glyphicon-calendar"></span>    </span>  </div>  <script type="text/javascript">    $(function () {      $('#datetimepicker').datetimepicker({format:'MMM-DD-YYYY'});    });  </script>  <br>  <div id="room">    <%= f.simple_fields_for :rooms do |a| %>      <p class="day-number-element-selector"><b>Day&nbsp;<%= a.index.to_i + 1 %></b></p>      <div id="event">        <% a.simple_fields_for :events do |e| %>          <%= e.input :from %>        <% end %>      </div>        #add here!!!        <%= f.link_to_add "Add event", :events, data: {target: '#event'}, class: "btn btn-primary" %>        <%= a.input :room %>      <% end %>  </div>  

new_html.erb

<div class="row">    <div class="col-md-12">      <p>Create schedule</p>      <%= simple_nested_form_for(@schedule) do |f| %>        <%= render 'schedule_form', f: f %>        <%= f.submit "Create my schedule", class: "btn btn-primary" %>        <br>      <% end %>    </div>  </div>  

Give the following models:

class Schedule < ActiveRecord::Base    belongs_to :user    has_many :rooms    accepts_nested_attributes_for :rooms, allow_destroy: true    ...    class Room < ActiveRecord::Base    belongs_to :schedule    has_many :events    accepts_nested_attributes_for :events, allow_destroy: true    ...    class Event < ActiveRecord::Base    belongs_to :room    ...  

schedule_controller.rb

class SchedulesController < ApplicationController  ...    before_action :set_schedule,  only: %i(show edit update destroy)  ...    def new      @schedule = Schedule.new      room = @schedule.rooms.build      room.events.build    end      def create      @schedule = current_user.schedules.build(schedule_params)      if @schedule.save        flash[:success] = "schedule created!"        redirect_to root_url      else        render 'new'      end    end      def edit      @day_max = Room.where("schedule_id = ?", @schedule.id).maximum(:day)    end      def update      @schedule.rooms.maximum(:day)      if @schedule.update(schedule_params)        flash[:success] = "schedule updated!"        redirect_to root_url      else        render 'edit'      end    end      private        def schedule_params        params.require(:schedule).permit(:title, :departure_date, rooms_attributes: [:id, :_destroy, :room, :day, events_attributes: [:id, :_destroy, :from, :to, :title, :detail]])      end        def set_schedule        @schedule = Schedule.find(params[:id])      end  

No error have been displayed before adding link_to_add.

It would be appreciated if you could give me any suggestion.

Rails console like console for symfony

Posted: 31 Mar 2016 04:37 AM PDT

Is there any console for symfony like we have for rails? In rails console we can access database tables and use rails active record code to get data. For example in rails we can do something like this

User.first  User.last  User.all  

And these commands will result first, last and all users from user table. Is there any similar thing in symfony?

mina deploy to ubuntu, ERROR: json (1.8.3).

Posted: 31 Mar 2016 03:24 AM PDT

I use Mina deploy to ubuntu, but an error about json.

after mina deploy

       An error occurred while installing json (1.8.3), and Bundler cannot continue.         Make sure that `gem install json -v '1.8.3'` succeeds before bundling.   !     ERROR: Deploy failed.  -----> Cleaning up build         Unlinking current         OK     !     Command failed.         Failed with status 1 (19)  

my todo

  1. sudo apt-get install libgmp-dev but not work.

    root@iZ28nb9h6ovZ:~# sudo apt-get install libgmp-dev Reading package lists... Done Building dependency tree Reading state information... Done libgmp-dev is already the newest version. The following packages were automatically installed and are no longer required:

  2. delete Gemfile.lock, and bundle , then mina deploy, but not work.

  3. On my VPS. root@iZ28nb9h6ovZ:~# gem install json -v '1.8.3'

    Building native extensions. This could take a while... Successfully installed json-1.8.3 Parsing documentation for json-1.8.3 Installing ri documentation for json-1.8.3 Done installing documentation for json after 3 seconds 1 gem installed

after 3 todo, the error only about json. What should I do?

No comments:

Post a Comment