Wednesday, August 10, 2016

Rails new command | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

Rails new command | Fixed issues


Rails new command

Posted: 10 Aug 2016 07:42 AM PDT

I just downloaded Ruby on Rails through RailsInstaller. I've seen on a tutorial that to start a new project, I had to tap 'rails new' + the name of my new app on the terminal. But when I do that, I've got an error :

Error

The specified path was not found

Does anyone have an idea to help me ?

Thanks ;)

Sinatra + active records server start error

Posted: 10 Aug 2016 07:15 AM PDT

I used sinatra + active records for 2 weeks and it worked excellent, but now, when i'm trying to start my app.rb it gives error:

    /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-activerecord-2.0.9/lib/sinatra/activerecord.rb:33:in `registered': uninitialized constant ActiveRecord::ConnectionAdapters::ConnectionManagement (NameError)  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1400:in `block in register'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1398:in `each'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1398:in `register'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-contrib-1.4.6/lib/sinatra/reloader.rb:323:in `register'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:1969:in `register'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-1.4.7/lib/sinatra/base.rb:2030:in `register'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-activerecord-2.0.9/lib/sinatra/activerecord.rb:58:in `<module:Sinatra>'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/sinatra-activerecord-2.0.9/lib/sinatra/activerecord.rb:10:in `<top (required)>'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:127:in `require'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:127:in `rescue in require'  from /Users/Aldres/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'  from app.rb:5:in `<main>'  

What should I do?

How to exclude samples that are already sampled before

Posted: 10 Aug 2016 07:26 AM PDT

First, I am beginner as a developer using ruby-on-rails. I am using blahblah.sample(x) to get (x) samples from blahblah. What i want to do is, I am using a loop to put several different numbers in an array. I will use the sample method to get (x) numbers. Here is the point I don't want to put the same number many times in the array. I know that if i put the random numbers and use uniq method this problem will be solved, but I want to exclude the number that i have in the array before I put it in the array. How can I solve this problem? I want to recognize that I have the number in the array or not before I put the number inside the array.

What I am eventually trying to do is When I am getting 10 sample of users to analyze their data. So I don't want to analyze the user that is analyzed already. I want to recognize if they are analyzed or not.

Ruby on Rails - seed fram development database

Posted: 10 Aug 2016 07:19 AM PDT

I have deployed my Application to my website now. In my Development ENV, I have a table called cities and contains 47K cities/records. How can I seed all of these cities to my Production ENV.

I am only thinking to do a one time seed and only for cities database.

Render three different partials depending on button clicked

Posted: 10 Aug 2016 07:36 AM PDT

So I have a layout like this:

<div style="margin-top:50px;" class="wrapper">    <div class="optionscontainer btn-group btn-group-justified">      <a style="background-color:#4183D7;" href="#" class="options btn btn-primary"><i class="fa fa-book optionseach" aria-hidden="true"></i>All posts</a>      <a style="background-color:#59ABE3;" href="#" class="options btn btn-primary"><i class="fa fa-rss optionseach" aria-hidden="true"></i>all stories</a>      <a style="background-color:#81CFE0;" href="#" class="options btn btn-primary"><i class="fa fa-users optionseach" aria-hidden="true"></i>all books</a>    </div>    <%= render 'all_posts' %>  </div>  

At the moment i have a partial being rendered all_posts.

I have three partials in total, I want a different partial to be rendered depending on the button clicked.

For example if i click the button for:

<a style="background-color:#4183D7;" href="#" class="options btn btn-primary"><i class="fa fa-book optionseach" aria-hidden="true"></i>All books</a>  

I want to render a partial called render 'all_books'

How to route a sub-domain to a certain page using ruby on rails

Posted: 10 Aug 2016 07:39 AM PDT

I want to redirect a sub-domain to a certain url using rails example: login.localhost:3000 to localhost:3000/login

direct database query with select_all using place holders

Posted: 10 Aug 2016 07:09 AM PDT

I need to make a query with select_all, something like this:

query << "SELECT blah blah FROM blah blah WHERE status_id IN(?, ?)"  query << " AND end_date IS NULL "  ...  ActiveRecord::Base.connection.select_all(query.join, STATUS_1, STATUS_2)  

This of course does not work.

What is the right way to do this?

Rails - how to add multiple bookings for same user

Posted: 10 Aug 2016 06:53 AM PDT

I'm building an events app using Rails. At the moment the booking process only allows for one user to book one place per booking. I need to add the facility whereby a User can make multiple/group bookings at once. So, not only do I need a 'quantity' function I also need this to tally with the price. I've trawled SO and Google trying to find the answers but have gotten nowhere for something which is pretty common for most sites.

I assume I need a method of some kind (in the model?) -

  def total_amount      @booking.quantity * @event.price  end  

So, if someone wants to book for 10 spaces on an event which costs £10 per space then the total amount should tally to £100.

Do I use methods in my model/controller or do I need some javascript for the process of reflecting the price per group booking?

Here's the MVC code for the bookings -

Booking.rb

     class Booking < ActiveRecord::Base        belongs_to :event      belongs_to :user            end  

bookings_controller.rb

    class BookingsController < ApplicationController        before_action :authenticate_user!        def new          # booking form          # I need to find the event that we're making a booking on          @event = Event.find(params[:event_id])          # and because the event "has_many :bookings"          @booking = @event.bookings.new          # which person is booking the event?          @booking.user = current_user          #@booking.quantity = @booking.quantity          #@total_amount = @booking_quantity.to_f * @event_price.to_f        end           def create          # actually process the booking          @event = Event.find(params[:event_id])          @booking = @event.bookings.new(booking_params)          @booking.user = current_user          #@total_amount = @booking.quantity.to_f * @event.price.to_f            Booking.transaction do                @event.reload              if @event.bookings.count > @event.number_of_spaces              flash[:warning] = "Sorry, this event is fully booked."              raise ActiveRecord::Rollback, "event is fully booked"              end           end                  if @booking.save                # CHARGE THE USER WHO'S BOOKED              # #{} == puts a variable into a string              Stripe::Charge.create(amount: @event.price_pennies, currency: "gbp",                  card: @booking.stripe_token, description: "Booking number #{@booking.id}")                flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          else              flash[:error] = "Payment unsuccessful"              render "new"          end            if @event.is_free?                @booking.save!              flash[:success] = "Your place on our event has been booked"              redirect_to event_path(@event)          end      end            private        def booking_params          params.require(:booking).permit(:stripe_token, :quantity)      end        end  

new.html.erb (bookings)

                <% if @event.is_free? %>  <div class="col-md-6 col-md-offset-3" id="eventshow">    <div class="row">      <div class="panel panel-default">          <div class="panel-heading">              <h2>Your Booking Confirmation</h2>          </div>                  <div class="panel-body">                            <h1>Hi there</h1>                            <p>You have placed a booking on <%= @event.title %></p>                            <p>Your order number is <%= @booking.id %></p>                            <p>We hope you have a wonderful time. Enjoy!</p>                            <p>Love from Mama Knows Best</p>                  </div>                            <div class="panel-footer">                      <%= link_to "Home", root_path %>                    </div>      </div>    </div>  </div>                                          <% else %>    <div class="col-md-6 col-md-offset-3" id="eventshow">    <div class="row">      <div class="panel panel-default">          <div class="panel-heading">              <h2>Confirm Your Booking</h2>          </div>                <div class="panel-body">                        <p>Total Amount<%= @event.price %></p>                  <%= simple_form_for [@event, @booking], id: "new_booking" do |form| %>                             <span class="payment-errors"></span>                    <div class="form-row">                      <label>                        <span>Card Number</span>                        <input type="text" size="20" data-stripe="number"/>                      </label>                  </div>                    <div class="form-row">                    <label>                    <span>CVC</span>                    <input type="text" size="4" data-stripe="cvc"/>                    </label>                  </div>                    <div class="form-row">                      <label>                          <span>Expiration (MM/YYYY)</span>                          <input type="text" size="2" data-stripe="exp-month"/>                      </label>                      <span> / </span>                      <input type="text" size="4" data-stripe="exp-year"/>                  </div>              </div>              <div class="panel-footer">                       <%= form.button :submit %>                  </div>     <% end %>  <% end %>          </div>    </div>  </div>        <script type="text/javascript" src="https://js.stripe.com/v2/"></script>    <script type="text/javascript">    Stripe.setPublishableKey('<%= STRIPE_PUBLIC_KEY %>');    var stripeResponseHandler = function(status, response) {      var $form = $('#new_booking');        if (response.error) {      // Show the errors on the form      $form.find('.payment-errors').text(response.error.message);      $form.find('input[type=submit]').prop('disabled', false);      } else {      // token contains id, last4, and card type      var token = response.id;      // Insert the token into the form so it gets submitted to the server      $form.append($('<input type="hidden" name="booking[stripe_token]"     />').val(token));      // and submit      $form.get(0).submit();      }    };      // jQuery(function($)  { - changed to the line below    $(document).on("ready page:load", function () {        $('#new_booking').submit(function(event) {        var $form = $(this);          // Disable the submit button to prevent repeated clicks        $form.find('input[type=submit]').prop('disabled', true);          Stripe.card.createToken($form, stripeResponseHandler);          // Prevent the form from submitting with the default action        return false;      });    });  </script>  

Here is the schema for bookings and events -

create_table "bookings", force: :cascade do |t|  t.integer  "event_id"  t.integer  "user_id"  t.string   "stripe_token"  t.datetime "created_at",   null: false  t.datetime "updated_at",   null: false  t.integer  "quantity"     end       create_table "events", force: :cascade do |t|  t.string   "title"  t.string   "location"  t.date     "date"  t.time     "time"  t.text     "description"  t.string   "organised_by"  t.datetime "created_at",                         null: false  t.datetime "updated_at",                         null: false  t.integer  "user_id"  t.string   "image_file_name"  t.string   "image_content_type"  t.integer  "image_file_size"  t.datetime "image_updated_at"  t.integer  "category_id"  t.string   "url"  t.integer  "number_of_spaces"  t.integer  "price"  t.boolean  "is_free"  t.integer  "price_cents",        default: 0,     null: false  t.integer  "price_pennies",      default: 0,     null: false  t.string   "price_currency",     default: "GBP", null: false  t.boolean  "happened",           default: false    end     

I think, ideally, I need a supplementary partial form activated when a user clicks on 'Book the Event' which asks them to specify the number of spaces they wish to book for the event BEFORE proceeding to payment. Any assistance or push in the right direction would be appreciated.

Factory Girl link tables with foreign key

Posted: 10 Aug 2016 07:22 AM PDT

Want to create the related records for the related tables:

class Product < ActiveRecord::Base  has_one :product_cstm, :foreign_key=>'id_c'  end    class ProductCstm < ActiveRecord::Base  self.table_name = 'product_cstm'  self.primary_key = 'id_c'  belongs_to :product, :foreign_key=>'id_c'  end  

So tables are linked with Products.id and Product_cstm.id_c

I've created following factories:

FactoryGirl.define do   factory :product do     id_c { SecureRandom.uuid }   end  end    FactoryGirl.define do   factory :product do     accociation :product_cstm   end  end  

Is it possible to create factories (and records), where the UUID would be generated the same for both product.id and product_cstm.id_c?

Showing CanCanCan roles in dropdown for roles one can manage

Posted: 10 Aug 2016 07:03 AM PDT

I have a dropdown for changing the role of a user in my Rails 4.2 app with CanCanCan. The User::ROLES array of strings holds the different possible roles that a user can have. To display the roles in a dropdown:

<%= f.select :role, options_for_select((User::ROLES), @user.role) %>  

I want to limit the dropdown options to roles that the currently signed-in user can :manage according to CanCanCan. Roles that the current user does not have :manage permissions on should not be populated in the dropdown. Any guidance is appreciated.

edit:

Sean Huber's answer is perfect if comparing against the string literals. However, I realized the issue is that I define this array in my User model, but I need to be comparing against the roles that are set one level deeper in ability.rb. Here's an example of how permissions on the User model are set in ability.rb:

This makes sense, however I realized it won't really work since it's comparing to the literals in the User::ROLES array.

The code in ability.rb that sets roles access looks like this. I need to check against the specific role specified:

if user.role? :superadmin    can :manage, User, role: 'admin'  end  

How can I compare against the specific roles that the :superadmin tokenized role has :manage access over instead of the literals in User::ROLES?

The definition of ROLES from User.rb:

ROLES = %w[student teacher school district reseller admin superadmin god]

How to change the box color based on the class value

Posted: 10 Aug 2016 06:24 AM PDT

I have a code in a loop like this

<td id = box, class =<%= book_ty(article)%>><%= article.book_type %></td>  

When the book_ty equal to x the box will become red color, if it is y the box will be orange color. Now the colors are directly applied to article.book_type I want apply that colors to id

I define a method in articles.helper.rb i.e

def book_ty(article)   case article.book_type    when "x"       "x"    when "y"       "y"    when "z"       "z"  end  end  

in article.scss

.x {    color: red;  }  .y{    color: orange;  }  .z{    color: green;  }    #box {   width: 50px;   height: 50px;   display: inline;   margin-right: 10px;  }  

How to change the box color based on the class value?

Capybara : Integration test for an API between two rails apps

Posted: 10 Aug 2016 06:38 AM PDT

We are currently developping two rails apps that communicates via an API (made with Grape). This morning I worked on the 'server' app, and the changes I made results in an error 5OO on the staging of the 'client' app.

To adress that, I want to create a Jenkins job that check the synchronization between the two apps. The process could be this one:

  1. A push is detected on the app A (or B)
  2. Build both apps
  3. Run an integration test through both apps
  4. Deploy both apps

I'm looking for the best way to do that. I found that question and this one, but there wasn't that much information in the answers.

One of the main problems is the integration test itself: how can I test through two apps with capybara ?

How can I write method with question mark using define_method

Posted: 10 Aug 2016 05:49 AM PDT

I have user model that has many types (admin, normal, ..). And I make loop to define methods like admin? or normal? as the following:

class User    TYPES = %w(admin normal)    User::TYPES.each do |roleVal|      define_method(roleVal.to_sym) { self.role == roleVal }    end  end  

The above code is working for example User.first.admin, But I need to call it as User.first.admin?.

What's the syntax of define_method with question mark ? And if that's not possible using define_method, How to create methods with question mark in meta-programming ?

Simple form to calculate change(money) using Ruby on Rails

Posted: 10 Aug 2016 05:34 AM PDT

I have this code:

<form Name="calc_troco">             <p>Dinheiro: <input type=text Name="dinheiro"> - <input type=button value="Calcular Troco" OnClick="calc_troco.troco.value=eval(calc_troco.dinheiro.value - <%= @order.price %>)"> - <input type=text Name="troco">  </form>  

How to build a simple form in Ruby on Rails to perform the same function " onclick " and not refresh the page ?

No method error in spree_elasticsearch gem

Posted: 10 Aug 2016 05:15 AM PDT

I am using the spree_gem in my pet app. Now i need to implement the elastic search concept in that application, so i use the spree_elasticsearch but it shows the no method error in Spree::Taxons#show.

Gemfile

gem 'spree', github: 'spree/spree', branch: '3-0-stable'  # Provides basic authentication functionality for testing parts of your engine  gem 'spree_auth_devise', github: 'spree/spree_auth_devise', branch: '3-0-stable'  # gem 'spree_i18n', github: 'spree-contrib/spree_i18n', branch: '3-0-stable'    # gem 'spree_core', '~> 3.0', '>= 3.0.4'    gem 'spree_elasticsearch', github: 'javereec/spree_elasticsearch', branch: '3-0-stable'

Rails server not starting, because if missing pg gem. Deinstalled postgres, but am getting the same error

Posted: 10 Aug 2016 07:24 AM PDT

I am getting the error when trying to start the Rails 5 server.

Specified 'postgresql' for database adapter, but the gem is not loaded. Add gem 'pg' to your Gemfile (and ensure its version is at the minimum >required by ActiveRecord).

I deleted local postgres via brew, removed also the existing mac app. This is my Gemfile

source 'https://rubygems.org'    gem 'rails',        '5.0.0'  gem 'puma',         '3.4.0'  gem 'sass-rails',   '5.0.6'  gem 'uglifier',     '3.0.0'  gem 'coffee-rails', '4.2.1'  gem 'jquery-rails', '4.1.1'  gem 'turbolinks',   '5.0.0'  gem 'jbuilder',     '2.4.1'    group :development, :test do    gem 'sqlite3'    gem 'byebug',  '9.0.0', platform: :mri  end    group :development do    gem 'web-console',           '3.1.1'    gem 'listen',                '3.0.8'    gem 'spring',                '1.7.2'    gem 'spring-watcher-listen', '2.0.0'  end    group :production do    gem 'pg'  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  

I used

bundle install --without production

But I am still getting the same error. Can anyone help please?

Thanks, Zin

Validate method does not see dependencies

Posted: 10 Aug 2016 05:22 AM PDT

I want to have custom validation on Vote resource

class Vote < ActiveRecord::Base      include HasUser      belongs_to :votable, polymorphic: true         validates :votable, :vote_field, presence: true     validates :user_id, uniqueness: { scope: [:votable_id, :votable_type] }     validate :vote_permission      def vote_permission      errors.add(:permission, 'denied') if self.vote_permitted?    end      def vote_permitted?      self.user == self.votable.user       end        def down?     self.vote_field == -1     end      def up?      self.vote_field == 1     end  end  

In my specs I'm getting error Vote should validate that :user_id cannot be empty/falsy Failure/Error: self.user == self.votable.user Where I am wrong? What should I do to make this work?

This helped

  def vote_permitted?      if votable.present?        self.user == self.votable.user       else       false      end      end  

but is it a right desigion? Sorry for my English

Checking overlaps between times

Posted: 10 Aug 2016 05:08 AM PDT

I try to create validation that checks times overlapping.

  scope :overlapping_activity, ->(activity) { where("(start_on, end_on) OVERLAPS (?, ?)",                                                activity.start_on, activity.end_on }    validate :not_overlapping_activity      def not_overlapping_activity      if Activity.overlapping_activity(self).any?        errors.add(:base, "Zajęcie w tym okresie koliduje z innymi.")      end    end  

Error:

ERROR:  function pg_catalog.overlaps(time without time zone, time without time zone, unknown, unknown) is not unique  LINE 1: ...NT(*) FROM "activities" WHERE ((start_on, end_on) OVERLAPS (...  

I found this topic: Rails 3.1: Querying Postgres for records within a time range, but I cannot use it in my solution. While I try add timestamps in scope, it shows another syntax errors. Could someone show me how to properly resolve my issue?

How I tried use timestamp:

  scope :overlapping_activity, ->(activity) { where("(start_on::timestamp, end_on::timestamp) OVERLAPS (?, ?)",                                                timestamp activity.start_on, timestamp activity.end_on) }  

Rails / Stripe - missing template error in bookings controller

Posted: 10 Aug 2016 04:48 AM PDT

I'm building an events app using Rails and I'm attempting to create code which first checks that spaces are available when a user tries to book and, if so, then takes them through to book the event. I've hit the following error when trying to make a booking -

Missing template bookings/create

def find(*args)    find_all(*args).first || raise(MissingTemplate.new(self, *args))  end    def find_all(path, prefixes = [], *args)  

I'm not sure this has anything to do with the over booking situation as there should be spaces available.It's more to do with the Stripe code, I think. Here's the relevant code -

bookings_controller.rb

  class BookingsController < ApplicationController    before_action :authenticate_user!    def new      # booking form      # I need to find the event that we're making a booking on      @event = Event.find(params[:event_id])      # and because the event "has_many :bookings"      @booking = @event.bookings.new      # which person is booking the event?      @booking.user = current_user      #@booking.quantity = @booking.quantity      #@total_amount = @booking_quantity.to_f * @event_price.to_f    end    def create      # actually process the booking      @event = Event.find(params[:event_id])      @booking = @event.bookings.new(booking_params)      @booking.user = current_user      #@total_amount = @booking.quantity.to_f * @event.price.to_f        Booking.transaction do          @booking.save!          @event.reload          if @event.bookings.count > @event.number_of_spaces              flash[:warning] = "Sorry, this event is fully booked."              raise ActiveRecord::Rollback, "event is fully booked"          else              if @booking.save                    # CHARGE THE USER WHO'S BOOKED                  # #{} == puts a variable into a string                  Stripe::Charge.create(amount: @event.price_pennies, currency: "gbp",                      card: @booking.stripe_token, description: "Booking number #{@booking.id}")                    flash[:success] = "Your place on our event has been booked"                  redirect_to event_path(@event)              else                  flash[:error] = "Payment unsuccessful"                  render "new"              end                if @event.is_free?                    @booking.save!                  flash[:success] = "Your place on our event has been booked"                  redirect_to event_path(@event)              end            end       end      end      #def total_amount      #@total_amount = @booking.quantity * @event.price  

No comments:

Post a Comment