Sunday, May 22, 2016

Post with latest comment on top of index page - Ruby On Rails | Fixed issues

Post with latest comment on top of index page - Ruby On Rails | Fixed issues


Post with latest comment on top of index page - Ruby On Rails

Posted: 22 May 2016 07:18 AM PDT

I need to display post with latest made comment in it on top of page

Here is my posts controller part with index def

def index      @posts = Post.all.order("posts.created_at desc")      def new          @post = Post.new      end  end  

I read Rails docs and found .order and .where and I think those two are solutions for my problem but I am not sure how to use it

How to manually specify a :delete request in the URL?

Posted: 22 May 2016 07:02 AM PDT

Situation: I want to destroy the current session in Rails, and am currently signed into an admin model setup via devise.

I thought it would be enough to input site.io/admins/sign_out into the URL, but this assumes a GET request and doesn't work.

No route matches [GET] "/admins/sign_out"

A method: :delete request needs to be made to destroy the session.

Can something be done like site.io/admins/sign_out{action:delete}?

UPDATE

Per request, this is the route related to admin.

devise_for :admins  

How to solve the update bundler warning in rails when deploying to heroku?

Posted: 22 May 2016 06:50 AM PDT

How do I solve the following warning? I updated my ruby version to 2.3.1 and rails version to 4.2.6. I get this warning when I push my app to heroku.

remote:        Cleaning up the bundler cache.  remote:        Warning: the running version of Bundler is older than the version that created the lockfile. We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.  remote:        Removing mime-types-data (3.2016.0221)  

I removed the Gemfile.lock and ran bundle install and also tried to update the bundler but the warning never goes away .

suramai@rails-tutorial:~/workspace/converse (master) $ gem install bundler  Successfully installed bundler-1.12.4  1 gem installed  suramai@rails-tutorial:~/workspace/converse (master) $  

Change wildcard route based off an array from Rails 3 to Rails 4

Posted: 22 May 2016 06:48 AM PDT

In Rails 3, I have these:

# shop.rb  class Shop < ActiveRecord::Base    TYPES = %w(cafe restaurant)  end    # shops_controller.rb  class SpotsController < ApplicationController    def cafe    end      def restaurant    end  end    # routes.rb  resources :shops do    resources :reviews, :photos    member do      get *Shop::TYPES    end  end  

The idea is to generate get routes based off the Shop::TYPES array:

get :cafe  get :restaurant  

In any case when I create another new type in Shop, I won't have to update my routes.

I am upgrading to Rails 4. What is the equivalent to get *Shop::TYPES, because I couldn't find the answer?

Devise issue while starting rails app in production mode

Posted: 22 May 2016 05:51 AM PDT

I have a rails app on my server which runs perfectly when I do rails s -b domain.name but when I run rails s -b domain.name -e production or RAILS_ENV=production rails s -b domain.name I have this following error.

=> Booting Puma => Rails 4.2.6 application starting in production on http://domain.name:3000 => Run 'rails server -h' for more startup options => Ctrl-C to shutdown server Exiting /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:244:in 'rescue in load_dependency': /home/deploy/appname/app/controllers/users/confirmations_controller.rb:2: unknown regexp options - cfrat (SyntaxError) /home/deploy/appname/app/controllers/users/confirmations_controller.rb:7: unknown regexp options - cfrat /home/deploy/appname/app/controllers/users/confirmations_controller.rb:12: unknown regexp options - cfrat /home/deploy/appname/app/controllers/users/confirmations_controller.rb:13: syntax error, unexpected keyword_def, expecting ':' def show ^ /home/deploy/appname/app/controllers/users/confirmations_controller.rb:27: syntax error, unexpected keyword_end, expecting end-of-input from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:237:in 'load_dependency' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in 'require' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:360:in 'require_or_load' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:317:in 'depend_on' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:233:in 'require_dependency' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:472:in 'block (2 levels) in eager_load!' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:471:in 'each' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:471:in 'block in eager_load!' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:469:in 'each' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:469:in 'eager_load!' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:346:in 'eager_load!' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/finisher.rb:56:in 'each' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application/finisher.rb:56:in 'block in <module:Finisher>' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in 'instance_exec' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in 'run' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:55:in 'block in run_initializers' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:228:in 'block in tsort_each' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:350:in 'block (2 levels) in each_strongly_connected_component' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:431:in 'each_strongly_connected_component_from' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:349:in 'block in each_strongly_connected_component' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in 'each' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in 'call' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in 'each_strongly_connected_component' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:226:in 'tsort_each' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:205:in 'tsort_each' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:54:in 'run_initializers' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/application.rb:352:in 'initialize!' from /home/deploy/appname/config/environment.rb:5:in '<top (required)>' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in 'require' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in 'block in require' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in 'load_dependency' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in 'require' from /home/deploy/appname/config.ru:3:in 'block in <main>' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in 'instance_eval' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in 'initialize' from /home/deploy/appname/config.ru:in 'new' from /home/deploy/appname/config.ru:in '<main>' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in 'eval' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in 'new_from_string' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/builder.rb:40:in 'parse_file' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/server.rb:299:in 'build_app_and_options_from_config' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/server.rb:208:in 'app' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/server.rb:61:in 'app' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/server.rb:336:in 'wrapped_app' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rack-1.6.4/lib/rack/server.rb:272:in 'start' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/server.rb:80:in 'start' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:80:in 'block in server' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in 'tap' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in 'server' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in 'run_command!' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in '<top (required)>' from /home/deploy/appname/bin/rails:9:in 'require' from /home/deploy/appname/bin/rails:9:in '<top (required)>' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in 'load' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in 'call' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/client/command.rb:7:in 'call' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/client.rb:30:in 'run' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/bin/spring:49:in '<top (required)>' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/binstub.rb:11:in 'load' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/spring-1.7.1/lib/spring/binstub.rb:11:in '<top (required)>' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in 'require' from /home/deploy/.rbenv/versions/2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in 'require' from /home/deploy/appname/bin/spring:13:in '<top (required)>' from bin/rails:3:in 'load' from bin/rails:3:in '<main>'

The error seems to come from Devise auto generated files but I cannot figure out why it happens only in prodcution mode.

Rails auto-submit radio button with AJAX

Posted: 22 May 2016 05:44 AM PDT

I need to be able to filter categories that contain given brands. I have a model Brand, Category and Country and I have a HBTM relationship between them. I have radio buttons for each brand and I need to be able to filter the categories that the selected brand is included to. I want it to happen "on click", without submit button. I need to know how to make the radio buttons to send a request to the server for categories that contain that brand (from the clicked radio button) without submit button and respond with JavaScript and reload an HTML element with updated categories. I would appreciate any help or hint.

Controller:

class MulticountryController < ApplicationController  def index      @brands = Brand.includes(:categories, :countries)      @categories = Category.includes(:brands, :countries)      @countries = Country.includes(:brands, :categories)  end  

end

View:

<div class="container-brands" style="display: inline-block;">  <% @brands.each do |brand| %>      <div id="checkbox-brands">         <%= radio_button_tag(:brand, brand.id )  %><%= brand.name %>        </div>  <% end %>  

<div class="container-categories" style="display: inline-block;">  <% @categories.each do |category| %>     <div id="checkbox-category">         <%= radio_button_tag(:category, category.id) %><%= category.name %>        </div>  <% end %>  

Brands controller:

class BrandsController < ApplicationController  def update      @brand = Brand.find(params[:id])      @categories = @brand.categories          respond_to do |format|          format.js      end  end  

end

Routes:

Rails.application.routes.draw do  resources :brands  root 'multicountry#index'  

undefined method `_path' when using params

Posted: 22 May 2016 06:38 AM PDT

I'm new to Rails and currently I'm building a game app. My game contains multiple levels. I want the url of the game to contain the number of each level. For example:

http://localhost:3000/game1/play/1  http://localhost:3000/game1/play/2  

In order to achieve this, I understand that I need to use params, here's my code:

routes.rb:

Rails.application.routes.draw do      devise_for :users      resources :game1      get "/game1" => "game1#index"    get "/game1/play/:level" => "game1#play"    get "/game1/instruction" => "game1#instruction"        get "/pages/*page" => "pages#show"    get "/pages/about" => "pages#about"      root "pages#show", page: "home"    end  

controller:

class Game1Controller < ApplicationController        def index      end        def play            @game1 = Game1lv.find(params[:level])            @userid = current_user.id          @usergame1lv = User.where(id: @userid).limit(1).pluck(:game1lv)           if @usergame1lv == [nil]              @usergame1lv = 1          end            @game1l = Game1lv.where(:level => @usergame1lv).limit(1).pluck(:imagelink)          @game1a = Game1lv.where(:level => @usergame1lv).limit(1).pluck(:answer)          @game1link = @game1l[0].to_s          @game1answer = @game1a[0].to_s            @game1answer_user = params["answer"]            if @game1answer_user == @game1answer              redirect_to game1_play_path(@game1), :flash => { :success => "You are right!" }          else              #flash.now[:alert] = 'You are wrong! Lets try again!'          end        end        def instruction      end    end  

view:

<body><center>        <br><b>Answer: </b><br><br>        <%= form_tag game1_play_path(@game1), :method => :get, :id => "text_form" do %>            <%= text_field_tag "answer", "" ,class: 'textbox_game' %>          <br><br>          <%= submit_tag("Submit", :class => "button_game") %>        <% end %>      </center></body>  

Now when I go to the url:

http://localhost:3000/game1/play/1  

Rails show the error:

undefined method `game1_play_path' for #<#<Class:0x943de50>:0x9447720>  

Rails indicate that the error is at this line in the view file:

<%= form_tag game1_play_path(@game1), :method => :get, :id => "text_form" do %>  

Please show me what I'm doing wrong and why that method is undefined. Thanks in advance.

Active record, undefined method

Posted: 22 May 2016 05:13 AM PDT

I am getting undefined method error in my rails console if I try to get something from model SubQuantity
I have a model called Subquantity, right now in my model I have
SubQuantity.rb
belongs_to :product
belongs_to :cart
end
and I have an integer defined in SubQuantity model called sub_quantity. In my code I am trying to do something like this
subq = SubQuantity.where(product_id:@product.id, cart_id:current_user.cart.id)
in return I am getting this,
[#<SubQuantity:0x007fbbdc046d08
id: 4,
sub_quantity: 1,
product_id: 4,
cart_id: 6,
created_at: Sun, 22 May 2016 11:03:55 UTC +00:00,
updated_at: Sun, 22 May 2016 11:03:55 UTC +00:00>]
and whenever I try to do something like this,
subq.sub_quantity
I am getting this error,
NoMethodError: undefined method sub_quantity for
#<SubQuantity::ActiveRecord_Relation:0x007fbbdc04d838>.
This is not only with sub_quantity, I am getting exact errors for every thing in subq even with subq.id. What is wrong here ?

Neo4j, Capistrano deployment, Authentication error

Posted: 22 May 2016 04:05 AM PDT

I want to deploy a Rails application, using Neo4jrb, to production with Capistrano. During deployment the following error shows up:

DEBUG [5a528d81] Finished in 0.057 seconds with exit status 0 (successful).  INFO [acd66fd5] Running /usr/local/bin/chruby-exec 2.3.0 -- bundle exec rake assets:precompile as deploy@46.101.153.252  DEBUG [acd66fd5] Command: cd /home/deploy/projects/larp-tool/releases/20160522103925 && ( export RAILS_ENV="production" ; /usr/local/bin/chruby-exec 2.3.0 -- bundle exec rake assets:precompile )  DEBUG [acd66fd5]    rake aborted!  DEBUG [acd66fd5]    Neo4j::Server::Resource::ServerException: Expected response code 200 Error for request http://localhost:7474/db/data/, 401  DEBUG [acd66fd5]    /home/deploy/projects/larp-tool/shared/bundle/ruby/2.3.0/gems/neo4j-core-6.1.4/lib/neo4j-server/resource.rb:37:in `handle_response_error!'  /home/deploy/projects/larp-tool/shared/bundle/ruby/2.3.0/gems/neo4j-core-6.1.4/lib/neo4j-server/resource.rb:32:in `expect_response_code!'  /home/deploy/projects/larp-tool/shared/bundle/ruby/2.3.0/gems/neo4j-core-6.1.4/lib/neo4j-server/cypher_session.rb:86:in `initialize_resource'  ...  

I set the following credentials in neo4.yml:

production:    type: server_db    url: http://username:password@localhost:7474  

and also tried:

production:    type: server_db    url: http://localhost:7474    username: username    password: password  

I set up this credentials with the Neo4j REST Api, and when I run curl on the server everything seems fine:

curl http://username:password@localhost:7474/db/data/  

So, why is there an error during deployment?

How to add calback for gem`s model

Posted: 22 May 2016 03:58 AM PDT

I have my own app. And I use some gem. This gem has, for example, User model.

How I can add my custom callback (after_save) for User model (which defined in gem without and callback for this model)?

Purpose of auth-scheme in HTTP Authorization header

Posted: 22 May 2016 03:42 AM PDT

I have a question regarding the auth-scheme. I stumble across JSON Web Tokens and one of the official page:

https://jwt.io/introduction/

They use

Authorization: Bearer <token>  

In the past, I am familiar with the Authorization: JWT <token> and had assume that was correct until today, I read the official JWT webpage and they used Bearer <token> instead.

I was testing the Knock Rails gem: https://github.com/nsarno/knock and with this library, I was able to make a Postman request to my Rails API with random auth-scheme:

example 1

I could even get rid of the auth-scheme completely:

example 2

When I remove my JWT token from the Authorization header, however, it returns 401 Unauthorized response as expected, so I know it's...working?

example 3

So I began to think...is there a purpose to the auth-scheme ?

Is a library or web server suppose to honour/respect/enforce the correct usage of auth-scheme in the Authorization header?

I came across this Stackoverflow post in my quest for answer:

Custom HTTP Authorization Header

It showed the official format is:

credentials = auth-scheme #auth-param  

The example given was even more bizarre:

Authorization: FIRE-TOKEN apikey="0PN5J17HBGZHT7JJ3X82", hash="frJIUN8DYpKDtOLCwo//yllqDzg="  

I don't know if this qualifies as a programming question. I can blindly follow/use a third party library.

What's the purpose of the auth-scheme ?

I'm no cryptography/computer security expert.

Maybe someone can shed some light on the issue (or maybe non-issue?) ?

Rspec Failure - NameError: uninitialized constant Faker

Posted: 22 May 2016 03:35 AM PDT

I'm facing this Failures: in Rspec - with Mongodb as database and devise for user management. Couldn't understand whats the issue.

with this command

bundle exec rspec spec/models/user_spec.rb

      FFFF    Failures:      1) User        Failure/Error: email { Faker::Internet.email }         NameError:         uninitialized constant Faker       # ./spec/factories/users.rb:3:in `block (3 levels) in <top (required)>'       # ./spec/models/user_spec.rb:19:in `block (2 levels) in <top (required)>'      2) User        Failure/Error: email { Faker::Internet.email }         NameError:         uninitialized constant Faker       # ./spec/factories/users.rb:3:in `block (3 levels) in <top (required)>'       # ./spec/models/user_spec.rb:19:in `block (2 levels) in <top (required)>'      3) User        Failure/Error: email { Faker::Internet.email }         NameError:         uninitialized constant Faker       # ./spec/factories/users.rb:3:in `block (3 levels) in <top (required)>'       # ./spec/models/user_spec.rb:19:in `block (2 levels) in <top (required)>'      4) User        Failure/Error: email { Faker::Internet.email }         NameError:         uninitialized constant Faker       # ./spec/factories/users.rb:3:in `block (3 levels) in <top (required)>'       # ./spec/models/user_spec.rb:19:in `block (2 levels) in <top (required)>'    Finished in 0.00478 seconds (files took 2.1 seconds to load)  4 examples, 4 failures    Failed examples:    rspec ./spec/models/user_spec.rb:23 # User   rspec ./spec/models/user_spec.rb:24 # User   rspec ./spec/models/user_spec.rb:25 # User   rspec ./spec/models/user_spec.rb:26 # User   

with /spec/models/user_spec.rb

require 'spec_helper'      describe User do      before { @user = FactoryGirl.build(:user)}        subject { @user }        it { should respond_to(:email) }      it { should respond_to(:password) }      it { should respond_to(:password_confirmation) }      it { should be_valid }  end  

and spec/factories/users.rb

FactoryGirl.define do    factory :user do      email { Faker::Internet.email }      password "12345678"      password_confirmation "12345678"    end  end  

Gemfile

source 'https://rubygems.org'      # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.4'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks  # gem 'turbolinks'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  # gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc    gem 'mongoid', '~> 5.1.0'    #Api gems  gem 'active_model_serializers'  # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    # Use Unicorn as the app server  # gem 'unicorn'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug'    gem "factory_girl_rails"    gem 'ffaker'  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'      # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'  end    group :test do    gem "rspec-rails"  end    gem "devise"  

Error while executing shell script of copiying a directory in ruby if the directory is having a space in it

Posted: 22 May 2016 04:12 AM PDT

Lets say I have a directory with name 'test folder' and when I tried to make a copy of it using ruby script it threw an error.

Here is what I tried:

irb(main):001:0>`cp -R test\ folder folder`


Output:


usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory => ""

Heroku logs confirm an email is being sent, but emails do not show up in mail box (production only)

Posted: 22 May 2016 03:56 AM PDT

After submitting a form in the development environment, the application sends an email to my email address. In the production environment, Heroku logs are reporting the email is being sent, but when I check the mailbox the email is not there. Here is my configuration:

application.yml

GMAIL_USERNAME: "christopherpelnar@gmail.com"  GMAIL_PASSWORD: "sevenmississippi"  

user_mailer.rb

class UserMailer < ApplicationMailer    default from: "christopherpelnar@gmail.com"      def customer_email(message)      @message = message      mail(to: "christopherpelnar@gmail.com", subject: "Message from your website" )    end    end  

messages_controller.rb

  def create      @message = Message.new(message_params)      if @message.save        UserMailer.customer_email(@message).deliver_now        redirect_to '/message_sent'      else        redirect_to '/'      end    end  

production.rb

config.action_mailer.default_url_options = { :host => 'stormy-wildwood-29407.herokuapp.com' }  config.action_mailer.perform_deliveries = true  config.action_mailer.raise_delivery_errors = false  config.action_mailer.default :charset => "utf-8"  config.action_mailer.smtp_settings = {    address: "smtp.gmail.com",    port: 587,    domain: "gmail.com",    authentication: "plain",    enable_starttls_auto: true,    user_name: ENV["GMAIL_USERNAME"],    password: ENV["GMAIL_PASSWORD"]  }  

Heroku logs

2016-05-22: UserMailer#customer_email: processed outbound mail in 238.2ms  2016-05-22: Sent mail to christopherpelnar@gmail.com (158.2ms)  2016-05-22:  2016-05-22: Date: Sun, 22 May 2016 09:43:29 +0000  2016-05-22: From: christopherpelnar@gmail.com  2016-05-22: To: christopherpelnar@gmail.com  2016-05-22: Message-ID: <17f4181751_3.mail>  2016-05-22: Subject: Message from your website  2016-05-22: Mime-Version: 1.0  2016-05-22: Content-Type: text/html;  2016-05-22:  charset=UTF-8  2016-05-22: Content-Transfer-Encoding: 7bit  

The problem is only in production and does not have a problem being sent through localhost:3000

How to fix and test a race-condition in my Rails 4 model

Posted: 22 May 2016 07:06 AM PDT

I had the following code in my model. Someone rightly pointed out that the make_default! method could cause a race condition:

class State < ActiveRecord::Base    def make_default!      State.update_all(default: false)      update!(default: true)    end  end  

because if two people are updating the record at the same time, two State objects could end up being set to default: true.

I used this workaround by using ActiveRecord locks:

class State < ActiveRecord::Base    def make_default!      # Prevent race condition using database-level locks.      State.transaction do        others = State.where.not(id: id).lock(true).first        current = State.where(id: id).lock(true).first          others.update_all(default: false) unless others.nil?        current.update!(default: true)      end    end  end  

but someone pointed out that this could cause other potential bugs. I'm wondering what the best way to implement locks would be, as well as how I'd go about testing the model spec (using RSpec)?

Any help much appreciated :) thanks!

How to upload image using CkEditor and Rails

Posted: 22 May 2016 01:48 AM PDT

I'v installed this https://github.com/tsechingho/ckeditor-rails lib into my Rails application. I would like to use CkEditor image upload functionality, but i'dont know how to write the backend logic, how to handle request, save file and send a response back to CkEditor to display uploaded image.

The CkEditor's configuration is the following:

  CKEDITOR.replace( 'editor1', {        language: 'en',        filebrowserImageUploadUrl : "/upload",        filebrowserUploadUrl : "/upload",    });  

Rails function

def upload    @func_num = params["CKEditorFuncNum"]    @ck_editor = params["CKEditor"]      render :layout => false  end  

Deploy rails app with capistrano rbenv unicorn

Posted: 22 May 2016 02:32 AM PDT

I have problem staring unicorn during deploy. The stack trace is the same as if I execute from "app_name"/current directory:

bundle exec rails c production

deployer@cloud-number-nine:~/qna/current$ bundle exec rails c production  [DEPRECATION] the dotenv-deployment gem is deprecated. See https://github.com/bkeepers/dotenv-deployment#readme.  /home/deployer/qna/releases/20160521190207/app/serializers/votable_serializer.rb:5:in `<class:VotableSerializer>': undefined method `root=' for VotableSerializer:Class (NoMethodError)      from /home/deployer/qna/releases/20160521190207/app/serializers/votable_serializer.rb:2:in `<top (required)>'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `require'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `block in require'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:240:in `load_dependency'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `require'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:360:in `require_or_load'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:317:in `depend_on'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:233:in `require_dependency'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:472:in `block (2 levels) in eager_load!'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:471:in `each'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:471:in `block in eager_load!'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:469:in `each'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:469:in `eager_load!'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/engine.rb:346:in `eager_load!'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/application/finisher.rb:56:in `each'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/application/finisher.rb:56:in `block in <module:Finisher>'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:30:in `instance_exec'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:30:in `run'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:55:in `block in run_initializers'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `call'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'      from /home/deployer/.rbenv/versions/2.3.0/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/initializable.rb:54:in `run_initializers'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/application.rb:352:in `initialize!'      from /home/deployer/qna/releases/20160521190207/config/environment.rb:5:in `<top (required)>'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `require'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `block in require'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:240:in `load_dependency'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `require'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/application.rb:328:in `require_environment!'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:142:in `require_application_and_environment!'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:67:in `console'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:39:in `run_command!'      from /home/deployer/qna/shared/bundle/ruby/2.3.0/gems/railties-4.2.5/lib/rails/commands.rb:17:in `<top (required)>'      from bin/rails:9:in `require'      from bin/rails:9:in `<main>'  

Capfile:

# Load DSL and set up stages  require 'capistrano/setup'    # Include default deployment tasks  require 'capistrano/deploy'  require 'capistrano/rbenv'  require 'capistrano/bundler'  require 'capistrano/rails'  require 'capistrano/sidekiq'  require 'capistrano3/unicorn'  require 'whenever/capistrano'  require 'thinking_sphinx/capistrano'    Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }  

deploy.rb

# config valid only for current version of Capistrano  lock '3.5.0'    set :application, 'qna'  set :repo_url, 'git@github.com:khataev/qna.git'    # Default deploy_to directory is /var/www/my_app_name  set :deploy_to, '/home/deployer/qna'  set :deploy_user, 'deployer'    # Default value for :linked_files is []  set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/private_pub.yml', 'config/private_pub_thin.yml', '.env')    # Default value for linked_dirs is []  set :linked_dirs, fetch(:linked_dirs, []).push('log', 'tmp/pids', 'tmp/cache', 'tmp/sockets', 'public/system', 'vendor/bundle', 'public/uploads')    # rbenv  set :rbenv_type, :user # or :system, depends on your rbenv setup  set :rbenv_ruby, '2.3.0'    set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec"  # set :rbenv_map_bins, %w(rake gem bundle ruby rails)  set :rbenv_roles, :all # default value  set :bundle_binstubs, nil    namespace :deploy do    desc 'Restart application'    task :restart do      on roles(:app), in: :sequence, wait: 5 do        # execute :touch, release_path.join('tmp/restart.txt')        invoke 'unicorn:restart'      end    end      after :publishing, :restart  end    namespace :private_pub do    desc 'Start private_pub server'    task :start do      on roles(:app) do        within current_path do          with rails_env: fetch(:rails_env) do            execute :bundle, 'exec thin -C config/private_pub_thin.yml start'          end        end      end    end      desc 'Stop private_pub server'    task :stop do      on roles(:app) do        within current_path do          with rails_env: fetch(:rails_env) do            execute :bundle, 'exec thin -C config/private_pub_thin.yml stop'          end        end      end    end      desc 'Restart private_pub server'    task :restart do      on roles(:app) do        within current_path do          with rails_env: fetch(:rails_env) do            execute :bundle, 'exec thin -C config/private_pub_thin.yml restart'          end        end      end    end  end    after 'deploy:restart', 'private_pub:restart'  after 'deploy:restart', 'thinking_sphinx:restart'  

unicorn/production.rb

# paths  app_path = '/home/deployer/qna'  working_directory "#{app_path}/current"  pid               "#{app_path}/current/tmp/pids/unicorn.pid"    # listen  listen '/tmp/unicorn.qna.sock', backlog: 64    # logging  stderr_path 'log/unicorn.stderr.log'  stdout_path 'log/unicorn.stdout.log'    # workers  worker_processes 2    # use correct Gemfile on restarts  before_exec do |_server|    ENV['BUNDLE_GEMFILE'] = "#{app_path}/current/Gemfile"  end    # preload  preload_app true    before_fork do |server, _worker|    # the following is highly recomended for Rails + "preload_app true"    # as there's no need for the master process to hold a connection    ActiveRecord::Base.connection.disconnect! if defined?(ActiveRecord::Base)      # Before forking, kill the master process that belongs to the .oldbin PID.    # This enables 0 downtime deploys.    old_pid = "#{server.config[:pid]}.oldbin"    if File.exist?(old_pid) && server.pid != old_pid      begin        Process.kill('QUIT', File.read(old_pid).to_i)      rescue Errno::ENOENT, Errno::ESRCH        # someone else did our job for us      end    end  end    after_fork do |_server, _worker|    ActiveRecord::Base.establish_connection if defined?(ActiveRecord::Base)  end  

votable serializer

My opinion that problem lies between rbenv and unicorn, but I'm not shure...

how to create alias of table name in Rails ActiveRecords

Posted: 22 May 2016 01:56 AM PDT

select user_id,  max(perception_score) as max, min(perception_score) as min from temp_user_notes group by user_id as t1;      

I am trying to convert this sql query in rails active record but having a hard time to create aliases

Errors when migrating heroku

Posted: 22 May 2016 01:39 AM PDT

Im attempting to rake my migrations on my heroku distro. im getting this error:

rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    PG::UndefinedTable: ERROR:  relation "plants" does not exist  : ALTER TABLE "images" ADD CONSTRAINT "fk_rails_d5e1aedcb5"  FOREIGN KEY ("plant_id")  REFERENCES "plants" ("id")  

Some of my tables go through, but not this one, im not sure what is even going on here. It works in development, but not in production.

Here is my schema file:

ActiveRecord::Schema.define(version: 20160521081000) do      create_table "appointments", force: :cascade do |t|      t.string   "task"      t.datetime "time"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "categories", force: :cascade do |t|      t.string   "name"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.integer  "user_id"    end      create_table "cycles", force: :cascade do |t|      t.string   "title"      t.datetime "completed_at"      t.boolean  "completed"      t.integer  "tray_id"      t.datetime "created_at",   null: false      t.datetime "updated_at",   null: false      t.datetime "due_date"    end      add_index "cycles", ["tray_id"], name: "index_cycles_on_tray_id"      create_table "datalogs", force: :cascade do |t|      t.integer  "tray_id"      t.float    "ambcur"      t.float    "ambmin"      t.float    "ambmax"      t.float    "folcur"      t.float    "folmin"      t.float    "folmax"      t.float    "ph"      t.float    "heatmat"      t.float    "h202"      t.float    "tds"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      add_index "datalogs", ["tray_id"], name: "index_datalogs_on_tray_id"      create_table "events", force: :cascade do |t|      t.string   "name"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "grows", force: :cascade do |t|      t.string   "title"      t.text     "notes"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "category_id"      t.integer  "user_id"    end      create_table "images", force: :cascade do |t|      t.string   "file_id"      t.integer  "plant_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.string   "tray_id"    end      add_index "images", ["plant_id"], name: "index_images_on_plant_id"      create_table "nutrient_calcs", force: :cascade do |t|      t.string   "product"      t.integer  "vegtime"      t.integer  "flowertime"      t.float    "rezsize"      t.string   "rezunits"      t.boolean  "aerstone"      t.string   "outputunits"      t.integer  "nutrient_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end      add_index "nutrient_calcs", ["nutrient_id"], name: "index_nutrient_calcs_on_nutrient_id"      create_table "nutrients", force: :cascade do |t|      t.string   "title"      t.string   "manufacturer"      t.float    "price"      t.string   "unit"      t.datetime "created_at",   null: false      t.datetime "updated_at",   null: false    end      create_table "pages", force: :cascade do |t|      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "pics", force: :cascade do |t|      t.string   "title"      t.text     "description"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end      create_table "plant_cycles", force: :cascade do |t|      t.string   "title"      t.integer  "interval"      t.integer  "frequency"      t.integer  "plant_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      add_index "plant_cycles", ["plant_id"], name: "index_plant_cycles_on_plant_id"      create_table "plantdats", force: :cascade do |t|      t.float    "ambtemp"      t.float    "foltempcur"      t.float    "foltempmin"      t.float    "foltempmax"      t.float    "ph"      t.float    "heatmat"      t.integer  "tds"      t.float    "h202"      t.integer  "plant_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.float    "ambtempmin"      t.float    "ambtembmax"    end      add_index "plantdats", ["plant_id"], name: "index_plantdats_on_plant_id"      create_table "plants", force: :cascade do |t|      t.string   "title"      t.text     "notes"      t.integer  "category_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.string   "species"      t.integer  "tray_id"      t.integer  "species_id"      t.integer  "user_id"    end      add_index "plants", ["category_id"], name: "index_plants_on_category_id"    add_index "plants", ["tray_id"], name: "index_plants_on_tray_id"    add_index "plants", ["user_id"], name: "index_plants_on_user_id"      create_table "schedules", force: :cascade do |t|      t.integer  "schedulable_id"      t.string   "schedulable_type"      t.date     "date"      t.time     "time"      t.string   "rule"      t.string   "interval"      t.text     "day"      t.text     "day_of_week"      t.datetime "until"      t.integer  "count"      t.datetime "created_at"      t.datetime "updated_at"    end      create_table "species", force: :cascade do |t|      t.string   "name"      t.text     "description"      t.integer  "plant_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end      add_index "species", ["plant_id"], name: "index_species_on_plant_id"      create_table "tasks", force: :cascade do |t|      t.integer  "plant_id"      t.integer  "tray_id"      t.string   "title"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.datetime "due_date"    end      add_index "tasks", ["plant_id"], name: "index_tasks_on_plant_id"    add_index "tasks", ["tray_id"], name: "index_tasks_on_tray_id"      create_table "tray_cycles", force: :cascade do |t|      t.string   "title"      t.integer  "tray_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      add_index "tray_cycles", ["tray_id"], name: "index_tray_cycles_on_tray_id"      create_table "trays", force: :cascade do |t|      t.string   "title"      t.text     "notes"      t.integer  "category_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "user_id"      t.integer  "rescap"    end      add_index "trays", ["category_id"], name: "index_trays_on_category_id"      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false      t.integer  "user_id"      t.string   "firstname"      t.string   "lastname"      t.string   "username"    end      add_index "users", ["email"], name: "index_users_on_email", unique: true    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true    end  

Also, my app gets pushed to Heroku, but when I go to 'sign_up', I get the error from the heroku logs:

2016-05-22T07:53:31.678059+00:00 app[web.1]: ActionView::Template::Error (undefined method `firstname' for #<User:0x007fa667e33798>):  2016-05-22T07:53:31.678049+00:00 app[web.1]:   2016-05-22T07:53:31.678060+00:00 app[web.1]:     25:   2016-05-22T07:53:31.678061+00:00 app[web.1]:     26:           <div class="field">  2016-05-22T07:53:31.678062+00:00 app[web.1]:     27:             <%= f.label 'First Name' %><br />  2016-05-22T07:53:31.678063+00:00 app[web.1]:     28:             <%= f.text_field :firstname, autofocus: true, rows: 10, cols: 10, class: 'form-control', placeholder: 'ENTER FIRST NAME' %>  2016-05-22T07:53:31.678064+00:00 app[web.1]:     29:           </div>  2016-05-22T07:53:31.678065+00:00 app[web.1]:     30:   2016-05-22T07:53:31.678065+00:00 app[web.1]:     31:           <div class="field">  

Can anyone help me figure this out? Many thanks :)

Angular material not working in Ruby on rails

Posted: 22 May 2016 02:51 AM PDT

Hi im currently working on a demo app and im currently working on ruby on rails, i want to implement angular material for my front end but when importing angular.js and angular.css like this. <%= stylesheet_link_tag 'application', media: 'all'%> <%= javascript_include_tag 'application', media: 'all'%>

and my application.js consist of.

//= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . //= require angular-material

and my application.css has.

*= require_self *= require_tree . *= require angular-material

when trying to use the sample on angular material button. it only display the text . for example the button.

<!DOCTYPE html>      <html lang="en">      <head>      <meta charset="UTF-8">      <%= stylesheet_link_tag 'application', media: 'all'%>      <%= javascript_include_tag 'application', media: 'all'%>      <%= csrf_meta_tags %>      <title>DEMO RUBY ON RAILS</title>      <h2>DEMO RUBY ON RAILS</h2>          <p>HELLO <%= @name %></p>          <%= link_to('HELLO INDEX RUBY',{:action => 'hello'})%><br/>          <%= link_to('HELLO WITH PARAMETERS RUBY',{:action => 'hello', :page =>5, :id=>20})%>           <md-button md-no-ink class="md-primary">Primary (md-noink)</md-button      </head>      <body>      </body>      </html>  

it only display the button with text Primary. it does not display the button itself.

enter image description here

i really appreciate your answers. thanks

rails: autoload files inside engine's lib directory

Posted: 22 May 2016 03:04 AM PDT

I am working on this rails application with an engine which is sort of sub application adding some more routes to my existing application.

The concept is so powerful, thanks to rails.

But I am facing this weird challenge to autoload file changes inside my engines lib directory in development mode. Every time I make a change inside app directory of engine be it model or controller , it works flawlessly, but no changes to any files under lib directory get's picked up. Is there a way I can do this ? Thanks for your help.

Rails 4.2.1, Using Collections With Partials Causes Items Displayed To Be Repeated Based On Number Of Items

Posted: 22 May 2016 12:40 AM PDT

I'm running into a weird issue here. I'm running Rails 4.2.1 & I'm using the Rails Crash Course book by Anthony Lewis and am following the instructions outlined in the book. The link for the book instructions are found here via Google Books.

So in the instructions he says to move the following code block into a partial called "_post.html.erb"

<% @posts.each do |post| %>    <h2><%= link_to post.title, post %></h2>    <p><i><%= friendly_date post.created_at %></i></p>    <p><%= post.body %></p>    <p>    <%= link_to 'Edit', edit_post_path(post) %>    <%= link_to 'Destroy', post, method: :delete,            data: { confirm: 'Are you sure?' } %>    </p>    <% end %>  

He then says that you can run the following code to basically activate the partial.

<%= render :partial => 'post', :collection => @posts %>    // or the simplified version ...    <%= render @posts %>  

However when I do this, the items displayed on the page get repeated by the number of items. So in this case, I have 3 items and they get repeated 3 times. I have attached a screenshot.

However when the code is not removed into a partial and no collections are being used, then it works fine. In other words, having the code inside the view's "index.html.erb" file, there are no repetitions of the items being displayed.

Can anyone help me out with what is going on here? I would really appreciate it!

Ruby On Rails - Make text green if there is >

Posted: 22 May 2016 02:09 AM PDT

So I am learning rails. I am building image-board as my first project.

Basically I need to change text color if there is > in text

Here is picture how it should look like

ActiveRecord::ConnectionNotEstablished for new project

Posted: 22 May 2016 05:08 AM PDT

I made a wrong choice and now I am sticked at the middle of my project I used ruby 5.0.0rc1, and while I start my project with rubymine I get "ActiveRecord::ConnectionNotEstablished"

I also get an error message while I type rake db:create :

Gregoires-MacBook-Pro:p1 gregoire$ rake db:create  Rake tasks not supported by 'pg' adapter  Couldn't create database for {"adapter"=>"pg", "pool"=>5, "timeout"=>5000, "database"=>"pg"}  rake aborted!  ActiveRecord::Tasks::DatabaseNotSupported: Rake tasks not supported by 'pg' adapter  

my database/yml :

# SQLite version 3.x  #   gem install sqlite3  #  #   Ensure the SQLite 3 gem is defined in your Gemfile  #   gem 'sqlite3'  #  default: &default    adapter: 'pg'    pool: 5    timeout: 5000    development:    <<: *default    database: 'pg'    test:    <<: *default    database: 'pg'    production:    <<: *default    database: 'pg'  

I am newbie with ror , any help will be appreciated (please detail)

greg

Nginx/Unicorn ignoring Unicorn logging config

Posted: 22 May 2016 01:14 AM PDT

I have my config setup in nginx to use unicorn, I then have my unicorn config setup to log to /var/log/unicorn/unicorn.log. But for some reason the logs are still showing in /var/log/nginx/access.log instead (with a variety of other access/error files).

I've seen some options for setting up logging in nginx directly (as seen below), but it seems like that would be skipping unicorn, which could be relevant. Am I incorrectly setting up my unicorn log files?

access_log /var/log/nginx/access.log;  error_log /var/log/nginx/error.log;  

Here are my current config files

/etc/nginx/sites-available/rails

upstream app {    server unix:/var/run/unicorn.sock fail_timeout=0;  }    server {    listen 443 ssl;    server_name www.example.org;      root /home/rails/source/public;      try_files $uri/index.html $uri @app;      location @app {      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header Host $http_host;      proxy_redirect off;      proxy_pass http://app;    }      # ssl stuff here    add_header Strict-Transport-Security max-age=15768000;      error_page 500 502 503 504 /500.html;    client_max_body_size 4G;    keepalive_timeout 10;  }    server {    listen 80;    server_name www.example.org www.example2.org;      root /home/rails/source/public;      try_files $uri/index.html $uri @app;      location @app {      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;      proxy_set_header Host $http_host;      proxy_redirect off;      proxy_pass http://app;    }      error_page 500 502 503 504 /500.html;    client_max_body_size 4G;    keepalive_timeout 10;  }  

/etc/unicorn.conf

listen "unix:/var/run/unicorn.sock"  worker_processes 4  user "rails"  working_directory "/home/rails/source"  pid "/var/run/unicorn.pid"  stderr_path "/var/log/unicorn/unicorn.log"  stdout_path "/var/log/unicorn/unicorn.log"  

/etc/default/unicorn

# Change paramentres below to appropriate values and set CONFIGURED to yes.  CONFIGURED=yes    # Default timeout until child process is killed during server upgrade,  # it has *no* relation to option "timeout" in server's config.rb.  TIMEOUT=60    # Path to your web application, sh'ld be also set in server's config.rb,  # option "working_directory". Rack's config.ru is located here.  APP_ROOT=/home/rails/source    # Server's config.rb, it's not a rack's config.ru  CONFIG_RB=/etc/unicorn.conf    # Where to store PID, sh'ld be also set in server's config.rb, option "pid".  PID=/var/run/unicorn.pid  RAILS_ENV="production"  UNICORN_OPTS="-D -c $CONFIG_RB -E $RAILS_ENV"    PATH=/usr/local/rvm/rubies/ruby-2.2.2/bin:/usr/local/sbin:/usr/bin:/bin:/sbin:/usr/local/rvm/bin:/usr/local/rvm/gems/ruby-2.2.2@global/bin:/usr/local/rvm/gems/ruby-2.2.2/bin/  export GEM_HOME=/usr/local/rvm/gems/ruby-2.2.2  export GEM_PATH=/usr/local/rvm/gems/ruby-2.2.2:/usr/local/rvm/gems/ruby-2.2.2@global  DAEMON=/usr/local/rvm/gems/ruby-2.2.2/bin/unicorn  

Rails, model method returning array instead of iterating over the results

Posted: 21 May 2016 11:41 PM PDT

new ruby on rails user here. I have a question about the following few lines of code.

First example in view.

<% sailing.travelling_parties.each do |party| %>    <% party.party_registers.each do |reg| %>      <%= reg.user.detailed_user.first_name %>    <% end %>  <% end %>  

When I run it in the in view, i get my expected result which is multiple names printed out. When I move it to the model and change it to the following,

Second example, in model. The ** represents what I'm actually trying to accomplish in this entire example.

class Sailing < ActiveRecord::Base    ...    def gather_data   self.travelling_parties.each do |party|    party.party_registers.each do |reg|      reg.user.detailed_user.first_name      ** use a variable to count loop iterations **    end   end  end  

Second example, in View

<%= sailing.gather_data %>  

This is printing out an array filled with the 'travelling_parties' I am trying to iterate over, not what I had expected at all! So, obviously it only loops once regardless of how many names are in the sailing record.

Can any shed any light on why this is happening, and how I can get it to work like the first example, without actually putting my business logic in the view?

Thanks

"undefined method `model_name' for..." error when using nested resources and simple_form, ruby on rails

Posted: 21 May 2016 11:49 PM PDT

enter code hereI get an "undefined method `model_name' for {:url=>"/possibilities/65/date_events/new"}:Hash" error, when I use simple_form in nested resources.

This is my date_events/new.html.erb:

<%= simple_form_for([@possibility, @dateevent, url: new_possibility_date_event_path]) do |f| %>  

I once tried this:

<%= simple_form_for([@possibility, @dateevent]) do |f| %>  

I got this error-message:

undefined method `date_events_path' for #<#<Class:0x007ffb4165e138>:0x007ffb42056f78>  

My routes:

        event_possibilities GET    /events/:event_id/possibilities(.:format)                     possibilities#index                              POST   /events/:event_id/possibilities(.:format)                     possibilities#create        new_event_possibility GET    /events/:event_id/possibilities/new(.:format)                 possibilities#new       edit_event_possibility GET    /events/:event_id/possibilities/:id/edit(.:format)            possibilities#edit            event_possibility GET    /events/:event_id/possibilities/:id(.:format)                 possibilities#show                              PATCH  /events/:event_id/possibilities/:id(.:format)                 possibilities#update                              PUT    /events/:event_id/possibilities/:id(.:format)                 possibilities#update                              DELETE /events/:event_id/possibilities/:id(.:format)                 possibilities#destroy                       events GET    /events(.:format)                                             events#index                              POST   /events(.:format)                                             events#create                    new_event GET    /events/new(.:format)                                         events#new                   edit_event GET    /events/:id/edit(.:format)                                    events#edit                        event GET    /events/:id(.:format)                                         events#show                              PATCH  /events/:id(.:format)                                         events#update                              PUT    /events/:id(.:format)                                         events#update                              DELETE /events/:id(.:format)                                         events#destroy      possibility_date_events GET    /possibilities/:possibility_id/date_events(.:format)          date_events#index                              POST   /possibilities/:possibility_id/date_events(.:format)          date_events#create   new_possibility_date_event GET    /possibilities/:possibility_id/date_events/new(.:format)      date_events#new  edit_possibility_date_event GET    /possibilities/:possibility_id/date_events/:id/edit(.:format) date_events#edit       possibility_date_event GET    /possibilities/:possibility_id/date_events/:id(.:format)      date_events#show                              PATCH  /possibilities/:possibility_id/date_events/:id(.:format)      date_events#update                              PUT    /possibilities/:possibility_id/date_events/:id(.:format)      date_events#update                              DELETE /possibilities/:possibility_id/date_events/:id(.:format)      date_events#destroy                possibilities GET    /possibilities(.:format)                                      possibilities#index                              POST   /possibilities(.:format)                                      possibilities#create              new_possibility GET    /possibilities/new(.:format)                                  possibilities#new             edit_possibility GET    /possibilities/:id/edit(.:format)                             possibilities#edit                  possibility GET    /possibilities/:id(.:format)                                  possibilities#show                              PATCH  /possibilities/:id(.:format)                                  possibilities#update                              PUT    /possibilities/:id(.:format)                                  possibilities#update                              DELETE /possibilities/:id(.:format)                                  possibilities#destroy                         root GET    /    

Any advices? Thanks in advance!

A possible problem might be, that I have two different nested resources, like this:

  resources :events do      resources :possibilities    end      resources :possibilities do      resources :date_events    end  

edit: Here is my create action for possibility. It redirects to:

  redirect_to new_possibility_date_event_path(@possibility)    def create    @possibility = Possibility.new    @possibility.event_id = params[:event_id]      if @possibility.save      else      render 'new'    end    redirect_to new_possibility_date_event_path(@possibility)  end  

edit 2: Here is my date_events controller:

  def new      @dateevent = DateEvent.new      @datelist = "Test"      @date = params[:date] ? Date.parse(params[:date]) : Date.today      @first_calendar_day = @date.beginning_of_month.beginning_of_week(:monday)      @last_calendar_day = @date.end_of_month.end_of_week(:monday)      @weeks = (@first_calendar_day..@last_calendar_day).to_a.in_groups_of(7)    end      def create      @possibility = Possibility.find(params[:possibility])      @datelist = params[:date].split(",")      @datelist.each do |date|        params[:date_event][:date] = date        @dateevent = DateEvent.new(dateevents_params)        @dateevent.save      end      redirect_to kalender_path    end  end    private    def dateevents_params    params.require(:date_event).permit(:date)  end  

update gem version that is specified in another gem dependency

Posted: 21 May 2016 09:53 PM PDT

In my Gemfile, I'm including a gem that has a .gemspec that uses the pessimistic operator ~> to specify a version of the gem. However, I need to use a newer version of the gem. In my case I'm using spree 3-0-stable that has activemerchant set to '~> 1.47.0' https://github.com/spree/spree/blob/3-0-stable/core/spree_core.gemspec#L22 but I need use active merchant '~> 1.59.0'

I tried to specify version 1.59.0 in my Gemfile but bundle complains with:

You have requested: activemerchant ~> 1.59.0

The bundle currently has activemerchant locked at 1.47.0. Try running bundle update activemerchant

If you are updating multiple gems in your Gemfile at once, try passing them all to bundle update

But the command bundle update activemerchant will only update to 1.47.x.

What's the rails-y way of accomplishing this? Aside from forking spree myself and updating the .gemspec? Obviously updates to the activemerchant gem might break the spree gem. But I can test with my app.

Swap values and keys in certain places in Ruby? [on hold]

Posted: 21 May 2016 08:05 PM PDT

I am trying to build a memory game and I need some way to display the "cards" that the player has gotten right. I was thinking about just swaping the keys and values or creating a temporary hash but I can't seem to make either of those work. This is only my first week learning how to code so I know that everything is a mess. Any help would be appreciated.

Ruby on Rails acts_as_votable gem

Posted: 22 May 2016 05:49 AM PDT

I am trying to create a voting system using acts_as_votable gem in Rails 4. I have three nominees to be voted from and I want a voter to choose from any of those three and vote only one nominee.acts_as_votable gem allows voter to vote multiple nominees. How do I restrict to only one nominee?

1 comment:

  1. Post With Latest Comment On Top Of Index Page - Ruby On Rails >>>>> Download Now

    >>>>> Download Full

    Post With Latest Comment On Top Of Index Page - Ruby On Rails >>>>> Download LINK

    >>>>> Download Now

    Post With Latest Comment On Top Of Index Page - Ruby On Rails >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete