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?

Wednesday, March 30, 2016

when force_ssl is on and I get 503 Service Unavailable: Back-end server is at capacity error after deployment | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

when force_ssl is on and I get 503 Service Unavailable: Back-end server is at capacity error after deployment | Fixed issues


when force_ssl is on and I get 503 Service Unavailable: Back-end server is at capacity error after deployment

Posted: 30 Mar 2016 07:40 AM PDT

I am trying to enforce ssl to be available on the entire site. This is why I have added: config.force_ssl = true config.ssl_options = {hsts: {expires: 3600}} to the application.rb file. Unfortunately after deployment I get the white screen of death. Nothing in the logs to indicate that the server is being hit, but in the network tab of the browser I see the request being made to http://staging.my_domain.com/admin and the status code: 503 Service Unavailable: Back-end server is at capacity. I checked every log that comes to mind and don't see any requests logging. I cannot figure out what is wrong. Just to clarify- before adding force_ssl = true, the website would load both on http:// and https://, so I presume that the certificate is installed correctly. Any clues? Thank you.

rails formular in bootstrap modal not processing

Posted: 30 Mar 2016 07:39 AM PDT

i've got a page movies/add

in this page I tried to use a bootstrap modal with a included form that should call the users/signup function

The form looks like this:

   <%= form_for User.new, :html => {:multipart => true, :class => "form-horizontal", :role => "form", :id => "signupform"}, :as => :user, :method => :post, :url => {}, :controller => :users, :action => :signup do |f| %>  

I don't get an error, it looks like it works fine, but in database there is nothing.

the controller function in useres_controller looks like this:

def signup  if request.post?    puts "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSs"    @user = User.new(user_params)    if @user.save      flash[:notice] = t("flash.signup")      #Weiterleitung nach erfolgreichem Anlegen      redirect_to :controller => :startsites, :action => "index"    end  else    @user = User.new  end  end  

functional tests admin section rails

Posted: 30 Mar 2016 07:29 AM PDT

I have a question concerning a functional test in rails.

For the front section, the actions are only index and show

#app/controller/themes_controller_rb  class ThemesController < ApplicationController      def index      @themes = Theme.active    end      def show      @theme = Theme.find(params[:id])    end      def new    end  end  

and the test

#test/integration/theme_controller_test.rb  require 'test_helper'    class ThemesControllerTest < ActionController::TestCase      def setup      @theme = create(:theme)    end      test "should assign variable on index" do      get :index      assert_response :success      assert_not_nil assigns(:themes)    end        test "should show a theme" do      get :show, {'id' => @theme}      assert_response :success      assert_not_nil assigns(:theme)    end    end  

No problem so far

For the admin section, all the CRUD actions exists so again index and show

#app/controllers/admin/themes_controller.rb  class Admin::ThemesController < Admin::AdminController      layout 'admin/admin'    before_action :admin_user      def index      @themes = Theme.all    end      def show      @theme = Theme.find(params[:id])    end    end  

and the tests are the same

#test/controllers/admin/theme_controller_test.rb  require 'test_helper'          class Admin::ThemesControllerTest < ActionController::TestCase          def setup          @theme = create(:theme)        end          test "should assign variable on index" do          get :index          assert_response :success          assert_not_nil assigns(:themes)        end            test "should show a theme" do          get :show, {'id' => @theme}          assert_response :success          assert_not_nil assigns(:theme)        end        end  

but for those latest tests, I have a 302 response instead of succes

 FAIL["test_should_assign_variable_on_index", Admin::ThemesControllerTest, 2016-03-16 06:50:16 +0000]   test_should_assign_variable_on_index#Admin::ThemesControllerTest (1458111016.61s)          Expected response to be a <success>, but was <302>          test/controllers/admin/themes_controller_test.rb:11:in `block in <class:ThemesControllerTest>'     FAIL["test_should_show_a_theme", Admin::ThemesControllerTest, 2016-03-16 06:50:16 +0000]   test_should_show_a_theme#Admin::ThemesControllerTest (1458111016.62s)          Expected response to be a <success>, but was <302>          test/controllers/admin/themes_controller_test.rb:18:in `block in <class:ThemesControllerTest>'  

What do I do wrong ? Thanks for help :)

Rails Bundler::GemRequireError when starting server

Posted: 30 Mar 2016 07:22 AM PDT

I'm getting this error whenever I try to run the server, not sure if it has to do with the js runtime, I'm using node and execjs installed for that.

/Users/me/.rvm/gems/ruby-2.2.2@global/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'rails-api'. (Bundler::GemRequireError)  from /Users/me/.rvm/gems/ruby-2.2.2@global/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'  from /Users/me/.rvm/gems/ruby-2.2.2@global/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'  from /Users/me/.rvm/gems/ruby-2.2.2@global/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'  from /Users/me/.rvm/gems/ruby-2.2.2@global/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'  from /Users/me/.rvm/gems/ruby-2.2.2@global/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'  from /Users/me/.rvm/gems/ruby-2.2.2@global/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'  from /Users/me/Documents/Rails/Paid/paid-api/config/application.rb:17:in `<top (required)>'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/railties-5.0.0.beta3/lib/rails/commands/commands_tasks.rb:88:in `require'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/railties-5.0.0.beta3/lib/rails/commands/commands_tasks.rb:88:in `block in server'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/railties-5.0.0.beta3/lib/rails/commands/commands_tasks.rb:85:in `tap'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/railties-5.0.0.beta3/lib/rails/commands/commands_tasks.rb:85:in `server'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/railties-5.0.0.beta3/lib/rails/commands/commands_tasks.rb:49:in `run_command!'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/railties-5.0.0.beta3/lib/rails/command.rb:20:in `run'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/railties-5.0.0.beta3/lib/rails/commands.rb:18:in `<top (required)>'  from /Users/me/Documents/Rails/Paid/paid-api/bin/rails:9:in `require'  from /Users/me/Documents/Rails/Paid/paid-api/bin/rails:9:in `<top (required)>'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/spring-1.6.4/lib/spring/client/rails.rb:28:in `load'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/spring-1.6.4/lib/spring/client/rails.rb:28:in `call'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/spring-1.6.4/lib/spring/client/command.rb:7:in `call'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/spring-1.6.4/lib/spring/client.rb:28:in `run'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/spring-1.6.4/bin/spring:49:in `<top (required)>'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/spring-1.6.4/lib/spring/binstub.rb:11:in `load'  from /Users/me/.rvm/gems/ruby-2.2.2/gems/spring-1.6.4/lib/spring/binstub.rb:11:in `<top (required)>'  from /Users/me/Documents/Rails/Paid/paid-api/bin/spring:13:in `require'  from /Users/me/Documents/Rails/Paid/paid-api/bin/spring:13:in `<top (required)>'  from bin/rails:3:in `load'  from bin/rails:3:in `<main>'  

My current Gemfile, pretty straight forward:

source 'https://rubygems.org'  gem 'rails', '>= 5.0.0.beta2', '< 5.1'  gem 'rails-api'  # Concurrent app server  gem 'puma'  gem 'activerecord-import', '~> 0.11.0'  # Message Queuing  gem 'aws-sdk', '~> 2'  # Load Balancing  gem 'shoryuken'  # Salesforce REST api  gem 'restforce'  # PAID ruby-gem  gem 'paid'  group :development, :test do    gem 'rubocop', '~> 0.39.0', require: false  end  group :development do    gem 'spring'  end  group :test do    gem 'rspec-core'  end  group :doc do    gem 'sdoc'  end  

My application.rb file, not much different:

require File.expand_path('../boot', __FILE__)  require "rails"  # Pick the frameworks you want:  require "active_model/railtie"  require "active_job/railtie"  # require "active_record/railtie"  require "action_controller/railtie"  require "action_mailer/railtie"  require "action_view/railtie"  require "action_cable/engine"  # require "sprockets/railtie"  require "rails/test_unit/railtie"  # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)  module PaidApi    class Application < Rails::Application      config.active_job.queue_adapter = :shoryuken    end  end  

Ruby on Rails - Unable to create a new profile for each user.

Posted: 30 Mar 2016 07:14 AM PDT

I'm building an events app with users who will each have a personal profile. I've set up a few users for the site but when I try and create and/or edit a profile for each user it refers me back to a flash message "That profile doesn't belong to you!" which is in reference to my first user profile which was set up and works fine.

I'm using Devise gem for initial set up but have built out from their with my own user controller. Here's the code from that controller -

class UsersController < ApplicationController before_action :authenticate_user! before_action :set_user before_action :owned_profile, only: [:edit, :update]

def new      @user = User.new  end      def show      @user = User.find(params[:id])    end    def create  end    #def edit      #@user = User.find(params[:id])  

Tuesday, March 29, 2016

How to Fetch Pdf Field Properties from downloads folder in ruby on rails from linux(ubuntu) vm | Fixed issues

How to Fetch Pdf Field Properties from downloads folder in ruby on rails from linux(ubuntu) vm | Fixed issues


How to Fetch Pdf Field Properties from downloads folder in ruby on rails from linux(ubuntu) vm

Posted: 29 Mar 2016 06:58 AM PDT

I have a pdf file in download folder , and i want to fetch particular field properties in that pdf file. How to fetch in ruby on rails

Creating a method that hits ActiveRestClient fake api

Posted: 29 Mar 2016 06:42 AM PDT

Working on a ruby on rails api and our team is using ActiveRestClient[gem] Need an example of how to write a method that touches the fake api and gets back the payload from the fake api.

The following code is my fake api. The first three fakes are j

class GuessTransaction < ActiveRestClient::Base    request_body_type :json      post :disbursements, '/disbursements', fake: {currency: "USD", amount: 12345.54}  end  

I've tried reaching it at GuessTransaction.disbursements but I'm getting back empty json instead of the stubbed data.

The culprit might be the serializer but I'm having trouble setting it up correctly.

class GuessTransactionSerializer < ActiveModel::Serializer    attributes :id, :amount, :merchant  end  

Can I use two different form in Wicked? one for create with a structure and other for update with more attributes?

Posted: 29 Mar 2016 06:39 AM PDT

I'm working with Rails 4 and I need to have two different form for wicked, or I think the solution is have to different form because currently I'm using a wicked for create orders. but I need when the user want update this order they can see more attributes than when they are creating an order.

So I don't know what is the best way for something like that because is not my first time implementing wicked but its my first time programming a logic like that.

Because when the user update the order I need to navigate between states and for that I'm using state machine so I'm a little confuse.

Any suggestion ?

Thanks for your time

how to add range filter to elasticserach-rails app

Posted: 29 Mar 2016 06:39 AM PDT

I installed elasticsearch demo app using this code

rails new searchapp --skip --skip-bundle --template https://raw.github.com/elasticsearch/elasticsearch-rails/master/elasticsearch-rails/lib/rails/templates/03-expert.rb  

then I made these modification

view

= form_tag search_path, method: 'get', role: 'search' do    input-group      = text_field_tag :min, params[:min], placeholder: 'min date'      = text_field_tag :max, params[:max], placeholder: 'max date'      %span.input-group-btn        = submit_tag 'Go', name: nil, class: 'btn btn-default'  

controller

class SearchController < ApplicationController    def index      options = {        min_date:      params[:min],        max_date:      params[:max],        category:       params[:c],        author:         params[:a],        published_week: params[:w],        published_day:  params[:d],        sort:           params[:s],        comments:       params[:comments]      }      @articles = Article.search(params[:q],options).page(params[:page]).results    end  end  

searchable concern

if query.present? && options[:less] && options[:more]    f = {        range: {            published_on: {                gte: options[:min_date],                lte: options[:max_date]            }        }    }  end  

When I submit the range form it send a separate request, clears the value I've entered in the search field and update the URL but doesn't filter the results.

where am I going wrong?

Ruby on Rails - Update multiple data in a table with select

Posted: 29 Mar 2016 07:01 AM PDT

(Rail 5 beta 3)

I have a table on an index page (action) of a view with around 15 columns. Some of them are for text and some of them are for integers only. Every entry of this list (table) will be filled out by a 'form_for' form (in new or edit action).

For editing or deleting there are links with each list entry in the index view leading to the corresponding show, edit or destroy actions. This all works well. Some of these entries are entered by a select with pulldown on the new or edit view. This works well, too.

But if one of these selects should be changed for more than one entry in the list it takes too much time to click on 'edit', change the select and click on submit at each list item. To make this a better user experience I would like to be able to change the selects in the list (table) directly. It would be good to have the select/pulldown in place. The change of the state or choosen entry should than be saved in place as well or with an extra button ("save changes") above/below the table.

To say it in short: I want to update multiple entries in a table in an index view without editig each single entry via edit view. The dates will be changed by a select and the data should be saved by a submit button on this page

Has anybody an idea how I can solve this?

Try to add new column into Posgres DB but only success when there is no data in table

Posted: 29 Mar 2016 05:55 AM PDT

I'm trying to add new column into the table by 'rake db:migrate',but it return nothing in cmd.Then i try 'rake db:migrate:status' this time it return the following...

C:\Sites\seas>rake db:migrate:status

database: seas_development     Status   Migration ID    Migration Name  --------------------------------------------------     up     20160323084854  Create equipment     up     20160329072332  Devise create users  

Below is inside my migration file...

class CreateEquipment < ActiveRecord::Migration    def change      create_table :equipment do |t|        t.string :name        t.string :equip_id        t.date :buy_date        t.string :brand        t.string :note        t.date :exp        t.string :status        t.string :serial        t.float :price        t.string :pic_id        t.string :ownby          t.timestamps null: false      end      add_column :equipment, :process ,:string    end  end  

This only happen if there exist some data in the table,otherwise migration work fine. Any suggestion ?

Within a feature spec, how to test that a Devise mailer is called successfully?

Posted: 29 Mar 2016 05:44 AM PDT

I have a feature test for user registration. How do I test that Devise confirmation instructions are sent correctly? I don't need to test the content of the email, only that the mailer has been called.

I am sending mails in the background.

#user.rb      def send_devise_notification(notification, *args)    devise_mailer.send(notification, self, *args).deliver_later  end  

I have tried a few approaches that work for other mailers, including

it "sends the confirmation email" do    expect(Devise.mailer.deliveries.count).to eq 1  end  

and

it "sends the confirmation email" do    message_delivery = instance_double(ActionMailer::MessageDelivery)    expect(Devise::Mailer).to receive(:confirmation_instructions).and_return(message_delivery)    expect(message_delivery).to receive(:deliver_later)  end  

none of which are working as expected for Devise messages.

What am I doing wrong?

remove subdomain from form

Posted: 29 Mar 2016 06:38 AM PDT

I'm using a constraint to set a subdomain for pages in my app

get '/', to: 'referal#new', constraints: { subdomain: 'keystrategy' }  

It brings me to keystrategy.[mypage]. This page only contains a few lines :

<%= form_for @referal, url: {action: "create", subdomain: false} do |f| %>    <%= f.text_field :referer %>    <input type="hidden" value="keystrategy">   <%= f.submit "Valider" %>  <% end %>  

But when I try to load this page, I get the following error :

No route matches {:action=>"create", :controller=>"referal", :subdomain=>"keystrategy"}  

What am I missing ? I thought the subdomain: false would prevent this

Ruby updating partial with a map: You have included the Google Maps API multiple times on this page. This may cause unexpected errors

Posted: 29 Mar 2016 05:40 AM PDT

I have a HAML file that renders partial that contains map show.html.haml:

      .row          .col-xs-12            .panel-group(style="margin-bottom: 0")              .stat-panel(style="padding: 5px; height:88.89px; margin:0")                .stat-cell.bg.col-md-1.col-sm-3.col-xs-3                  %i.fa.fa-map-marker.bg-icon.bg-icon-left{:style => "font-size:60px;line-height:80px;height:80px;"}                .stat-cell.bg.valign-middle(style="padding-left: 40px;")                  Geographic Summary              .panel.no-border.no-padding                = render partial: 'map_content', locals: {demographics: @demographics, listicle: @listicle}  

And that partial _map_content.html.haml contains map:

    .panel-body.no-border.no-padding{:style => "position:relative;height: 600px;"}        #map-container.widget-maps          /%script{:src => "assets/javascripts/bootstrap.min.js"}          /%script{:src => "assets/javascripts/pixel-admin.min.js"}          /%script{:src => "http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"}          /%script{:src => "http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.1/js/bootstrap.min.js"}          /%script{:src => "http://maps.google.com/maps/api/js?sensor=false"}          :javascript            var map;            var markers=[];            var coord = #{@coordinates};            var la = #{@current_lat};            var lo = #{@current_long};            function setMarkers(locations, lat, lon) {                    if (coord.length !=0){                    for (var i = 0; i < locations.length; i++) {                        var myLatLng = new google.maps.LatLng(locations[i][0], locations[i][1]);                        var marker = new google.maps.Marker({                                 position: myLatLng,                                 map: map,                                 animation: google.maps.Animation.DROP                        });                        markers.push(marker);                    }}                        var curLatLong =  new google.maps.LatLng(lat, lon);                        var current_marker = new google.maps.Marker({                                 position: curLatLong,                                 map: map,                                 animation: google.maps.Animation.DROP,                                 title: 'You are here'                        });                        markers.push(current_marker);            }          function reloadMarkers() {                 for (var i=0; i<markers.length; i++) {                     markers[i].setMap(null);                 }                 markers = [];                 setMarkers(coord, la, lo);        }            function init_map() {                var var_mapoptions = {                  mapTypeId: google.maps.MapTypeId.ROADMAP,                  center: new google.maps.LatLng(39.5202922,-96.2318707),                  zoom: 5                }                map = new google.maps.Map(document.getElementById("map-container"),                     var_mapoptions);                  setMarkers(coord, la, lo);                  var mc = new MarkerClusterer(map, markers);                document.getElementById('q-itm').addEventListener('click', reloadMarkers);        }      %script{:src=>"http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js"}        %script{:src => "https://maps.googleapis.com/maps/api/js?key=AIzaSyCi93_Ajfvl-ZwxPRwqVI98hcqfu2LF3Ic&callback=init_map"}      :cdata  

The logic is: the show.haml has another partial, that has Submit button. After a user enters info in that partial and clicks Submit, only the maps_content partial gets updated (not the whole page). However, I'm getting this error in console (though, everything works fine and I'm just afraid of possible run times errors if someone maybe will click on submit many times): You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

I understand that this happens because src=>... gets loaded multiple times in the same DIV, after Submit is clicked. I tried to move src=> upper, to the show file. But then the map would load on the whole page refresh only, but when I would click Submit, it won't load and DIV stands white without a map.

Any suggestions? Thank you

Rails Active Admin-I want to show selected members in my active admin

Posted: 29 Mar 2016 06:30 AM PDT

I have User table and a Member Table. I am creating a Community i.e. another model community. While creating Community I am selecting Users and data is saved in Member Table but when I edit the community the selected members are not visible.

Community Active Admin file has code :

f.input :members, :as => :select2_multiple, :collection => User.all.sort_by(&:id).collect {|p| [ p.screen_name, p.id ] }, include_blank: false  

I am overriding the update action of controller.

In Bluemix while pushing 'App staging failed in the buildpack compile phase'

Posted: 29 Mar 2016 06:35 AM PDT

I am trying to push rails App. But while pushing its throwing following Error

enter image description here

Please shares some ideas.

Thanks & Regards

No implicit conversion of nil into String on MessageVerifier

Posted: 29 Mar 2016 05:28 AM PDT

Recently I received new project (backend of iOS app, actually) that works on Ruby (Rails).

I have a part of code in model (user):

155:  def self.create_access_token(user)  156:    verifier.generate(user.id)  157:  end  

After some action that indirectly uses that part of code, in "Passenger" output I see following error that terminates everything:

TypeError (no implicit conversion of nil into String):    app/models/user.rb:156:in `create_access_token'    app/models/user.rb:139:in `access_token'    app/controllers/mailing_controller.rb:68:in `send_charts'  

verifier is an instance of ActiveSupport::MessageVerifier

I'm totally sure that user.id contains valid value (I've tested it with $stderr.puts)

I'm completely new to this language, it's hard for me to figure out why this error appears. Hope someone can help.

Thanks!

Syntax Error with rails unexpected ')'

Posted: 29 Mar 2016 05:38 AM PDT

Hi there I want to add a destroy action in post#show view I think I have creates the environment but when I place this code with a condition I have a message error.

<% if @user.comment == current_user %>     <% link_to @post_comment_path(post_id: @post.id, id: comment.id), method:    :delete, data: { confirm: "Are you sure?" } do %>     <i class="fa fa-trash"></i>   <% end %>   <% end %>  

I created a partial in post show#view which names _comments.html.erb

here it is

<p class="text-center">Poster un commentaire</p>        <%= simple_form_for [post, post.comments.new] do |f| %>          <%= f.error_notification %>          <%= f.input :content, label: "Commentaire"%>          <%= f.submit "Envoyer", class: "btn btn-primary" %>        <% end %>  

and it render like that <%= render 'comments' %>

and above the partial (in post show#view) I do an iteration like that

<ul class="list-unstyled">      <% @post.comments.each do |comment| %>     <li>        <p><% comment.content %></p>     <% end %>     </li>  </ul>  

But nothing appears when I create a new message, I don't userstand why.

I give your more code details

post.rb

has_many :comments, dependent: :destroy  

comment.rb

belongs_to :user  belongs_to :post  

The route is:

resources :posts do    resources :categories    resources :comments  end  

Comments controller is

class CommentsController < ApplicationController    before_action :set_post    def create    @comment = @post.comments.build(comment_params)    @comment.user_id = current_user.id      if @comment.save      flash[:success] = "You commented the hell out of that post!"      redirect_to :back    else      flash[:alert] = "There is a problem with your comment"      render root_path    end  end    def destroy    @comment = @post.comments.find(params[:id])      @comment.destroy    flash[:success] = "Comment deleted :("    redirect_to root_path  end    private    def set_post    @post = Post.find(params[:post_id])  end    def comment_params    params.require(:comment).permit(:content, :post_id, :user_id)  end  end  

Thank you so much for your help.

templates missing with mailer

Posted: 29 Mar 2016 06:57 AM PDT

I am new to using mailer and read a few tutorials but can't for the life of me work out why this this error is appearing

Missing template layouts/mailer with {:locale=>[:en], :formats=>[:text], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :haml]}. Searched in:    * "/Users/paulmcguane/RoR/barista/app/views"    * "/Users/paulmcguane/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/devise-3.5.6/app/views"  

new_record_notification.text.erb

Hi,    A new record has been added: <%= @record.name %>    Thanks  

model_mailer.rb

class ModelMailer < ApplicationMailer      # Subject can be set in your I18n file at config/locales/en.yml    # with the following lookup:    #    #   en.model_mailer.new_record_notification.subject    #    def new_record_notification(record)      @record = record      mail(to: 'email@address') do |format|        format.text      end    end  end  

Making gem for different rails(active_record) versions

Posted: 29 Mar 2016 05:17 AM PDT

I have a gem, what add some methods to ActiveRecord objects, and has dependencies of AR components. Of cource I want to make code fixes for different AR versions. I will use my gem with rails 3.2 and 4.2. And i want to add compatibility with other versions. What is the best way to organize version compatibility of the gem with rails? May be branches or major versioning for my gem.

Set Timezone For User Before Create Rails

Posted: 29 Mar 2016 06:49 AM PDT

I am attempting to implement correct time zone handling in Rails.

Every user has a different time zone, so each user's time zone exists in the database.

The problem: when I create a user, I pass onto the time zone what I get from the client.

The user have some fields like created, but I want to save the correct time when I create the user and not when I update the model.

This is my model:

require 'securerandom'    class User    include Mongoid::Document    include Mongoid::Paperclip      field :created, type: Time    field :time_zone, type: String      def set_created      self.created = Time.now.in_time_zone(self.time_zone)    end  end   

This is the Application Controller:

class ApplicationController < ActionController::API    include ActionController::HttpAuthentication::Token::ControllerMethods      around_filter :set_time_zone        def current_user      return unless params[:user_id]      @current_user ||= User.find(params[:user_id])    end      private      def set_time_zone(&block)      time_zone = current_user.try(:time_zone) || 'UTC'      Time.use_zone(time_zone, &block)    end         end  

I set around_filter yet I don't know how to pass the time_zone parameters into it. Currentuser doesn't work because the user is not created.

avoiding application.html.erb for flash notices on rails app landing page

Posted: 29 Mar 2016 05:38 AM PDT

I have designed two flash notices for my rails 4 application. First is supposed to appear on all pages (when an event occurs), so I have written it in my application.html.erb file. The second one should only appear on the landing page with its custom CSS.

Right now, both are showing on the landing page. How can I avoid first one (written in application.html.erb) only for my landing page?

(<unknown>): did not find expected node content while parsing a flow node at line 18 column 14 while running rake db:migrate

Posted: 29 Mar 2016 05:56 AM PDT

I am trying to run old Ruby on Rails project on my machine (Ubuntu). I installed rvm ruby 1.9.3-p551 and rails 2.3.2. After installing bundler, gems n etc; I ran rake db:migrate.

I am getting the following error, please help me out.

user@iam:~/Desktop/practice/Application$ rake db:migrate   rake aborted!  (<unknown>): did not find expected node content while parsing a flow node at line 18 column 14  Tasks: TOP => db:migrate => environment  (See full trace by running task with --trace)  

Rails 4.2 mountable engine loading dependencies twice

Posted: 29 Mar 2016 04:57 AM PDT

I'm building a Devise extension called devise-verifiable.

Following the instructions from Rails Engine Guide I ran this command:

rails new plugin devise_verifiable --mountable  

To start the project, I've created a first integration test to validate the project setup, but I'm getting these warnings when run rake test command:

/omitted@devise-verifiable/gems/devise-3.5.6/lib/devise.rb:109: warning: character class has duplicated range: /\A[^@\s]+@([^@\s]+\.)+[^@\W]+\z/  /omitted@devise-verifiable/gems/devise-3.5.6/lib/devise/rails/warden_compat.rb:2: warning: method redefined; discarding old request  /omitted@devise-verifiable/gems/warden-1.2.6/lib/warden/mixins/common.rb:17: warning: previous definition of request was here  /omitted@devise-verifiable/gems/devise-3.5.6/lib/devise/rails/warden_compat.rb:11: warning: method redefined; discarding old reset_session!  /omitted@devise-verifiable/gems/warden-1.2.6/lib/warden/mixins/common.rb:38: warning: previous definition of reset_session! was here  /omitted@devise-verifiable/gems/devise-3.5.6/lib/devise/rails.rb:50: warning: method redefined; discarding old respond_to?  /omitted@devise-verifiable/gems/actionpack-4.2.6/lib/action_dispatch/routing/routes_proxy.rb:22: warning: previous definition of respond_to? was here  /omitted@devise-verifiable/gems/devise-3.5.6/lib/devise/failure_app.rb:28: warning: method redefined; discarding old default_url_options  /omitted@devise-verifiable/gems/activesupport-4.2.6/lib/active_support/core_ext/class/attribute.rb:86: warning: previous definition of default_url_options was here  

After digging into this messages, I've noticed that the file test/dummy/config/application.rb is being loaded twice. One interesting thing about it is that I've removed the line requiring my lib in this file and still get the warnings and don't get undefined error.

lib/devise-verifiable.rb

require 'devise'  require "devise/verifiable/engine"  

lib/devise/verifiable/engine.rb

module Devise    module Verifiable      class Engine < ::Rails::Engine        isolate_namespace Devise::Verifiable      end    end  end  

test/test_helper.rb

# Configure Rails Environment  ENV["RAILS_ENV"] = "test"    require File.expand_path("../../test/dummy/config/environment.rb",  __FILE__)  ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)]  ActiveRecord::Migrator.migrations_paths << File.expand_path('../../db/migrate', __FILE__)  require "rails/test_help"    # Filter out Minitest backtrace while allowing backtrace from other libraries  # to be shown.  Minitest.backtrace_filter = Minitest::BacktraceFilter.new    # Configure capybara for integration testing  require 'capybara/rails'  Capybara.default_driver   = :rack_test  Capybara.default_selector = :css    # Load support files  Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }    # Load fixtures from the engine  if ActiveSupport::TestCase.respond_to?(:fixture_path=)    ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)    ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path    ActiveSupport::TestCase.fixtures :all  end  

test/dummy/config/application.rb

require File.expand_path('../boot', __FILE__)    require 'rails/all'    Bundler.require(*Rails.groups)  # the requive below (generated by rails plugin command) doesn't affect the result  # require 'devise-verifiable'    module Dummy    class Application < Rails::Application      config.active_record.raise_in_transactional_callbacks = true    end  end  

I think I didn't modify the initial structure created by rails plugin command (just added the devise dependency). Any idea on why the application.rb file is being loaded twice, (and then, getting those redefined warning messages)?

Why am I encountering a SQLite3::ConstraintException in my controller when adding to favourites? Favouriting a micropost based on Hartl tutorial

Posted: 29 Mar 2016 06:52 AM PDT

I have based my favouriting a micropost button on Hartl's follow user button.

I can go onto user's page and favourite a micropost once but as soon as I try to favourite a second, I am given a SQLite3::ConstraintException in FavouritesController#create. The constraint is:

UNIQUE constraint failed: favourites.favouriter_id, favourites.favourited_id.  

Why am I encountering this constraint?

Favourites Controller:

class FavouritesController < ApplicationController  before_action :logged_in_user    def create  @micropost = Micropost.find(params[:favourited_id])  current_user.favourite(@micropost)  redirect_to user_path (current_user)  end    def destroy  @micropost = Favourite.find(params[:id]).favourited  current_user.unfavourite(@micropost)  redirect_to user_path (current_user)  end      end  

Add to favourites form:

<%= form_for(current_user.favourites.build) do |f| %>    <div><%= hidden_field_tag :favourited_id, @user.id %></div>    <%= f.submit "Favourite" %>  <% end %>  

User Model:

has_many :favourites, class_name: "Favourite",foreign_key:"favouriter_id", dependent: :destroy  has_many :favouriting, through: :favourites, source: :favourited    def favourite(micropost)  favourites.create(favourited_id: micropost.id)  end    def unfavourite(micropost)      favourites.find_by(favourited_id: micropost.id).destroy  end    def favouriting?(micropost)     favourites.include?(micropost)  end  

User Controller:

def favouriting  @title = "Favourites"  @user = User.find(params[:id])  @microposts = @user.favouriting.paginate(page: params[:page])  render 'microposts/show_favourite'  end      def favouriter  @title = "Favourite"  @micropost = Micropost.find(params[:id])  @users = @micropost.favouriter.paginate(page: params[:page])  render 'microposts/show_favourite'  end   

Micropost model:

class Micropost < ActiveRecord::Base  belongs_to :user    has_many :favourites, class_name: "Favourite",foreign_key: "favourited_id", dependent: :destroy  has_many :favouriter, through: :favourites, source: :favouriter  

Javascript File Dependencies Not Being Resolved With Manifest Order

Posted: 29 Mar 2016 05:47 AM PDT

I'm currently in the process of reorganizing our Javascript/Coffeescript files in our Rails 4 application using this tutorial. Prior to this, because of my ignorance of the asset pipeline, we had most of our code in one giant coffeescript file. The goal is to break this giant file into logical, manageable parts.

Our application uses some general classes to define programing structures like a doubly-linked list. I wanted to put this in a separate file, app/assets/javascripts/misc_classes.coffee:

### ***********************************###  ### ******* General Classes ***********###  ### ***********************************###    #single node for doubly linked list  class Node    constructor: (data) ->      @data = data      prev = null      next = null    #Doubly-linked list class, to be used for front-end destinations  #Details: https://en.wikipedia.org/wiki/Doubly_linked_list  class DoublyList    constructor: () ->      @length = 0 #length of the current list      @head = null #first node of the list      @tail = null #last node of the list  ...  

The rest of our application code resides in app/assets/javascripts/custom/trips.coffee. The code in trips.coffee uses the Doubly-linked list class from the other javascript file described above:

### ***********************************###  ### ****** Custom Site Classes ********###  ### ***********************************###    class Trip    constructor: (id, editable) ->      @id = id #trip_id      @title = 'New Trip'      @cities = 0 #number of citites in trip      @countries = 0 #number of countries in trip      @distance = 0 #distance in KM      @days = 0 #duration of trip in days      @destinations = new DoublyList()  ...  

From the Rails Asset Pipeline Guide, the way to handle this dependency is via the application.js manifest file.

If you need to ensure some particular JavaScript ends up above some other in the concatenated file, require the prerequisite file first in the manifest. Note that the family of require directives prevents files from being included twice in the output.

So our application.js file looks like this:

//= require jquery  //= require jquery.turbolinks  //= require jquery_ujs  //= require jquery-ui/sortable  //= require jquery-ui/datepicker  //= require colorbox-rails  //= require jquery.readyselector  //= require turbolinks  //= require jquery.externalscript  //= require misc_classes  //= require_tree ./custom/.  

However, when I run the code, I get the following error in the console: Uncaught ReferenceError: DoublyList is not defined

Why is this happening? According to the other posts here, it appears I wrote the manifest file correctly. I can verify both files are included in the sites section in the correct order as well.

Thanks!

Rails, validate overlap range time

Posted: 29 Mar 2016 04:37 AM PDT

I'm doing an exercise. Let say I have Movie table (name:string, duration:decimal) duration: in second. I have a MovieSessions table, belongs_to:movie and have a start_time:datetime and belongs_to:room When create a new MoiveSession I need to validate that with a given room_id is there an overlaptime or not. Can you help me? Below is detail schema

  create_table "movie_sessions", force: :cascade do |t|      t.decimal  "price"      t.integer  "room_id"      t.integer  "movie_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.datetime "date_time"    end      add_index "movie_sessions", ["date_time", "room_id"], name: "index_movie_sessions_on_date_time_and_room_id", unique: true    add_index "movie_sessions", ["movie_id"], name: "index_movie_sessions_on_movie_id"    add_index "movie_sessions", ["room_id"], name: "index_movie_sessions_on_room_id"      create_table "movies", force: :cascade do |t|      t.string   "url"      t.string   "name"      t.string   "description"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.decimal  "duration"    end      create_table "rooms", force: :cascade do |t|      t.string   "name"      t.text     "description"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end  

Creating image with the same blurred image as background

Posted: 29 Mar 2016 04:32 AM PDT

How can I create the image as shown below using MiniMagick in Rails?

I wanted to display the image in a mobile app but figured it's better to offload the task to the server by preprocessing it as soon as users upload the image.

enter image description here

Rspec fails when testing view edit form

Posted: 29 Mar 2016 04:30 AM PDT

I'm working on my first rails app here and two of the generated tests don't pass:

Failures:      1) gardens/edit renders the edit garden form       Failure/Error: assert_select "input#garden_user_id[name=?]", "garden[user_id]"         Minitest::Assertion:         Expected at least 1 element matching "input#garden_user_id[name="garden[user_id]"]", found 0..         Expected 0 to be >= 1.       # ./spec/views/gardens/edit.html.haml_spec.rb:27:in `block (3 levels) in <top (required)>'       # ./spec/views/gardens/edit.html.haml_spec.rb:17:in `block (2 levels) in <top (required)>'      2) gardens/new renders new garden form       Failure/Error: assert_select "input#garden_user_id[name=?]", "garden[user_id]"         Minitest::Assertion:         Expected at least 1 element matching "input#garden_user_id[name="garden[user_id]"]", found 0..         Expected 0 to be >= 1.       # ./spec/views/gardens/new.html.haml_spec.rb:27:in `block (3 levels) in <top (required)>'       # ./spec/views/gardens/new.html.haml_spec.rb:17:in `block (2 levels) in <top (required)>'  

I'm not sure why this is. When I look at the test, I'm kind of surprised the path doesn't contain an id to edit (something like /gardens/#{@garden.id}/edit). When I try to edit the test accordingly rspec fails to run telling me that @garden isn't instantiated yet.

spec/views/gardens/edit.html.haml_spec.rb:

require 'rails_helper'    RSpec.describe "gardens/edit", type: :view do    before(:each) do      @garden = assign(:garden, Garden.create!(        :name => "MyString",        :square_feet => 1,        :zone => 1,        :garden_type => "MyString",        :user => nil      ))    end      it "renders the edit garden form" do      render        assert_select "form[action=?][method=?]", garden_path(@garden), "post" do          assert_select "input#garden_name[name=?]", "garden[name]"          assert_select "input#garden_square_feet[name=?]", "garden[square_feet]"          assert_select "input#garden_zone[name=?]", "garden[zone]"          assert_select "input#garden_garden_type[name=?]", "garden[garden_type]"          assert_select "input#garden_user_id[name=?]", "garden[user_id]"      end    end  end  

What do I have to do to make these tests pass?

Ruby use DynamoDB Local with AWS::Record::HashModel

Posted: 29 Mar 2016 04:26 AM PDT

app is build on aws-sdk v1. one of its ORM entity extend from AWS::Record::HashModel that persist on dynamodb. need to configure this to local Dynamodb. tried this settings How do you use DynamoDB Local with the AWS Ruby SDK?. but still its not working. checking credintial from amazon. fail to run without internet.

java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -inMemory  

config/initializers/aws.rb

AWS.config(    use_ssl: false,    access_key_id: 'cUniqueSessionID',    secret_access_key: '',    dynamo_db: { api_verison: '2012-08-10', endpoint: 'localhost', port: '8000' }   )  

aws cli works without any error

 aws --endpoint-url=http://localhost:8000 dynamodb list-tables  --region us-east-1  

Spree category pages in custom rails app

Posted: 29 Mar 2016 04:47 AM PDT

I have created a default rails app. I am beginner to spree.

I am not able to find the code for the pages which are coming by default in the spree app.

This is how I have created the app

gem install rails -v 4.2.2  gem install bundler  gem install spree_cmd  rails _4.2.2_ new mystore  cd mystore  spree install --auto-accept  

When I go to http://localhost:3000/t/categories/bags I get all the categories for this category.

But in my view I do not see any code. So from where are these coming from?

Please help.

Calling controller method in integration test Rails

Posted: 29 Mar 2016 04:29 AM PDT

How can i call a specific method from controller in integration tests. For example i have following lines in test/controller/testing.rb file which is running fine

 get :show, {employee_id: @employee.id}      assert_response :success  

But how can i call show method in integration test file ?

rails environment production not working no files loaded

Posted: 29 Mar 2016 03:45 AM PDT

in my Rails application all my js and css is in public folder.

in dev mode it works fine. but when I switch to production mode it dosn't work no css and js is found.

what could be the problem?

Which image has been accessed?

Posted: 29 Mar 2016 03:46 AM PDT

Is there a way to know which image has been accessed or loaded to a web page at which time? For example, if my page contains one image, and the page is loaded on ten different machines, where can I find a log that tells this image has been loaded ten times? I am using nginx.

rails migration production db not working well

Posted: 29 Mar 2016 03:25 AM PDT

I've got problems while migrating my database in production mode.

migrationfile looks like this:

class ChangeCourseDefaultsNull < ActiveRecord::Migration   def self.up     change_column :course_objects, :active, false, :default => 0   end     def self.down     change_column_null :course_objects, :active, true   end  end  

error is

== 20150720105700 ChangeCourseDefaultsNull: migrating  =========================  -- change_column(:course_objects, :active, false, {:default=>0})  rake aborted!  StandardError: An error has occurred, all later migrations canceled:    undefined method `to_sym'  

whats going wrong?