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?

1 comment:

  1. I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.
    Money manifestation

    ReplyDelete