Saturday, June 25, 2016

SQL injection in Rails in Where Clause | Fixed issues

SQL injection in Rails in Where Clause | Fixed issues


SQL injection in Rails in Where Clause

Posted: 25 Jun 2016 08:01 AM PDT

I have following line which was suspected of SQL injection by a static code analyzer:

Admin.joins(:accounts_admins).where(user_id: params[:user_u  ser_id], "members.account_id" => @account.id).first  

To me, it looks safe as its using parameterized query. Let me know if anyone think otherwise.

error creating new app on rails after bundle install, what should be done?

Posted: 25 Jun 2016 08:00 AM PDT

i am trying to make a new app on rails and i get this what should i do?

C:\Sites>rails new mousab    create    create  README.rdoc    create  Rakefile    create  config.ru    create  .gitignore    create  Gemfile    create  app    create  app/assets/javascripts/application.js    create  app/assets/stylesheets/application.css    create  app/controllers/application_controller.rb    create  app/helpers/application_helper.rb    create  app/views/layouts/application.html.erb    create  app/assets/images/.keep    create  app/mailers/.keep    create  app/models/.keep    create  app/controllers/concerns/.keep    create  app/models/concerns/.keep    create  bin    create  bin/bundle    create  bin/rails    create  bin/rake    create  bin/setup    create  config    create  config/routes.rb    create  config/application.rb    create  config/environment.rb    create  config/secrets.yml    create  config/environments    create  config/environments/development.rb    create  config/environments/production.rb    create  config/environments/test.rb    create  config/initializers    create  config/initializers/assets.rb    create  config/initializers/backtrace_silencers.rb    create  config/initializers/cookies_serializer.rb    create  config/initializers/filter_parameter_logging.    create  config/initializers/inflections.rb    create  config/initializers/mime_types.rb    create  config/initializers/session_store.rb    create  config/initializers/wrap_parameters.rb    create  config/locales    create  config/locales/en.yml    create  config/boot.rb    create  config/database.yml    create  db    create  db/seeds.rb    create  lib    create  lib/tasks    create  lib/tasks/.keep    create  lib/assets    create  lib/assets/.keep    create  log    create  log/.keep    create  public    create  public/404.html    create  public/422.html    create  public/500.html    create  public/favicon.ico    create  public/robots.txt    create  test/fixtures    create  test/fixtures/.keep    create  test/controllers    create  test/controllers/.keep    create  test/mailers    create  test/mailers/.keep    create  test/models    create  test/models/.keep    create  test/helpers    create  test/helpers/.keep    create  test/integration    create  test/integration/.keep    create  test/test_helper.rb    create  tmp/cache    create  tmp/cache/assets    create  vendor/assets/javascripts    create  vendor/assets/javascripts/.keep    create  vendor/assets/stylesheets    create  vendor/assets/stylesheets/.keep  run  bundle install  

C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/win32/registry.rb:71:in find': unkno wn encoding name - CP720 (ArgumentError) from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/win32/registry.rb:71:in ' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/win32/registry.rb:3:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/win32/resolv.rb:6:in' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/resolv.rb:169:in <class :Hosts>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/resolv.rb:166:in' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/resolv.rb:36:in <top (r equired)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/remote_fetcher. rb:6:in' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2 /lib/bundler/gem_remote_fetcher.rb:1:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2 /lib/bundler.rb:6:in' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:128:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:128:inrescue in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:39:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5 .1/lib/rails/generators/app_base.rb:330:inbundle_command' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5 .1/lib/rails/generators/app_base.rb:346:in run_bundle' from (eval):1:inrun_bundle' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li b/thor/command.rb:27:in run' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li b/thor/invocation.rb:126:ininvoke_command' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li b/thor/invocation.rb:133:in block in invoke_all' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li b/thor/invocation.rb:133:ineach' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li b/thor/invocation.rb:133:in map' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li b/thor/invocation.rb:133:ininvoke_all' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li b/thor/group.rb:232:in dispatch' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/thor-0.19.1/li b/thor/base.rb:440:instart' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5 .1/lib/rails/commands/application.rb:17:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5 .1/lib/rails/cli.rb:14:in' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:in require' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/rubygems/core_ext/kernel _require.rb:54:inrequire' from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5 .1/bin/rails:9:in <top (required)>' from C:/RailsInstaller/Ruby2.2.0/bin/rails:23:inload' from C:/RailsInstaller/Ruby2.2.0/bin/rails:23:in `'

Rails application images not displayed from Google Cloud

Posted: 25 Jun 2016 07:53 AM PDT

I am currently running my application in development mode. Although I am connected to Google Cloud storage and can upload images via Paperclip, the images do not seem to display on my browser in my view pages. I don't understand what's wrong.

I have not used Google Cloud before and I am struggling with it, although it seems to work fine behind the scenes. I checked the source code of the page, and everything turns up fine. But instead of the image the alt text shows up. Can anyone please point out, what maybe missing?

PS: I get a warning in my terminal

[fog][WARNING] Unrecognized arguments: fog_directory    

but that doesn't stop my application from writing into the storage bucket.

Rails grouped_collection_select how to scope some elements to only one element

Posted: 25 Jun 2016 07:38 AM PDT

I have 2 models:

Car_brand, and Brand_model that belongs_to Car_brand

My problem is how to get only specific Brand_model from specific Car_brand by grouped_collection_select.

As for now I have a working select that returns all Brand_models from selected Car_brands.

 = f.grouped_collection_select :cars, CarBrand.where(name: ['Audi','Fiat']).order(:name), :brand_cars, :name, :id, :name  

But what if I wanted all Audi brand_cars and only Fiat '500' ?

I think that this have to do with third element ':brand_cars' but, as it maps through given Car_brands, but I don`t know how to start it.

I will be glad for any help

How to close connection for channel with websocket-rails on server side

Posted: 25 Jun 2016 07:32 AM PDT

I am using websocket-rails with background job.

I have implemented channel with code in background process.

def establish_connection      counters.each do |counter|            counter.perform_some_method        WebsocketRails[:updates].trigger(:update, counter.row_count)        end      close_connection // How to implement this close connection for above updates channel connection   end  

In my frontend view. I have

$(function(){            var dispatcher = new WebSocketRails('localhost:3000/websocket',false);            channel = dispatcher.subscribe('updates');          channel.bind('update', function(data) {            $('#job_count').text(data);          });      });   

I want to close the channel from server side after loop finished. How to implement this close connection for above updates channel ? Please suggest.

Unicorn Rails require error

Posted: 25 Jun 2016 06:49 AM PDT

/usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/lib/unicorn.rb:56:in `eval'  /usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/lib/unicorn.rb:56:in `block in builder'  /usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:752:in `build_app!'  /usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:617:in `init_worker_process'  /usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:639:in `worker_loop'  /usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:508:in `spawn_missing_workers'  /usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:519:in `maintain_worker_count'  /usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/lib/unicorn/http_server.rb:283:in `join'  /usr/local/rvm/gems/ruby-2.3.1/gems/unicorn-5.1.0/bin/unicorn:126:in `<top (required)>'  /usr/local/rvm/gems/ruby-2.3.1/bin/unicorn:23:in `load'  /usr/local/rvm/gems/ruby-2.3.1/bin/unicorn:23:in `<main>'  /usr/local/rvm/gems/ruby-2.3.1@global/bin/ruby_executable_hooks:15:in `eval'  /usr/local/rvm/gems/ruby-2.3.1@global/bin/ruby_executable_hooks:15:in `<main>'  

I am getting the above unusal error in unicorn log all of sudden. And the Nginx is going into 504 Gateway Timeout

Undefined method in controller to display associations

Posted: 25 Jun 2016 06:46 AM PDT

I have a model called User and a model called Post

I have a controller:

class IntrestedController < ApplicationController    def intrested      post = Post.find(params[:post_id])      current_user.intresteds.create(post: post)      redirect_to post    end  end  

Interested Model:

class Intrested < ActiveRecord::Base    belongs_to :post    belongs_to :user  end  

User model

#created with devise  has_many :intresteds  has_many :posts, through: :interested  

Post model

class Post < ActiveRecord::Base    belongs_to :user    has_many :intresteds    has_many :users, through: :intresteds  end  

Migration

class CreateIntresteds < ActiveRecord::Migration    def change      create_table :intresteds do |t|        t.references :post, index: true, foreign_key: true        t.references :user, index: true, foreign_key: true          t.timestamps null: false      end      add_index :intresteds, [:post_id, :user_id], :unique => true    end  end  

On the show page for the Post I'm trying to show all the users that were interested in the post

def show   @post = Post.find(params[:id])   @intrested_users = @post.users  end  

But I'm getting this error:

undefined method `users' for #<Post:0x007f8a62bc0810>  

Here is how users click on a button to create the associations

<%= button_to(intrested_path, class:"btn btn-info btn-block") do %>    <%= hidden_field_tag 'post_id', @post.id %>    Intrested  <% end %>  

Javascript not working with Capybara and Selenium

Posted: 25 Jun 2016 06:24 AM PDT

I'm following Rails 4 in Action book and having some issues when running specs with selenium(both chrome driver and firefox).

There's a link on a page, which is supposed to execute request using JS:

<%= link_to "Add another file", new_attachment_path, remote: true,      id: "add_file", data: { params: { index: ticket.attachments.size } } %>  

Coffeecript:

$ ->    $("#add_file").on "ajax:success", (event, data) ->      $("#attachments").append data      $(this).data "params", { index: $("#attachments div.file").lenght }  

Controller action:

def new      @index = params[:index].to_i      @ticket = Ticket.new      @ticket.attachments.build      render layout: false  end  

Form:

<%= fields_for @ticket do |f| %>    <%= render partial: "form", locals: { f: f, index: @index } %>  <% end %>  

This all works in development mode, i.e. when I click "Add another file", request is executed. But it seems like in test no JS is executed at all in browser.

How do I troubleshoot this?

Rails migration + unique mysql index: Only one value can be true

Posted: 25 Jun 2016 06:20 AM PDT

I have a model that has a default field. Now I want to ensure, that only one entry can have default: true. On rails side I'm doing it with (see here http://stackoverflow.com/a/24928769/228370):

validates :default, uniqueness: true, if: :default  

But because this could lead to invalid records, when a lot of rows are inserted at the same time, I also want to create an unique index on mysql side in my migration:

add_index :emails, :default, unique: true  

But this index doesn't allow multiple records with default: false (or 0, its a tiny int). Is it possible to add a constraint in a migration, so that multiple false values are allowed, but only one true value is allowed?

Select first by date of each group of unique key pairs in rails

Posted: 25 Jun 2016 06:07 AM PDT

class User < ActiveRecord::Base    has_many :events    has_many :trainings, -> { distinct }, through: :events  end    class Event < ActiveRecord::Base    belongs_to :user    belongs_to :training  end    class Training < ActiveRecord::Base    has_many :events    has_many :user, -> { distinct },  through: :events  end    events table contains:    t.integer  "user_id"  t.integer  "training_id"  t.due      "date"  

Imagine the events table has the following user_id, training_id and due date

[ 1, 1, 25/06/16]  [ 1, 1, 25/06/15]  [ 1, 1, 25/06/14]    [ 1, 2, 25/06/16]  [ 1, 2, 25/06/15]  [ 1, 2, 25/06/14]    [ 2, 1, 25/06/16]  [ 2, 1, 25/06/15]  [ 2, 1, 25/06/14]    [ 2, 2, 25/06/16]  [ 2, 2, 25/06/15]  [ 2, 2, 25/06/14]  

I want to select the most recent value by due date of each of those "groups" (user & training key pairs).

i.e.

[ 1, 1, 25/06/16]  [ 1, 2, 25/06/16]  [ 2, 1, 25/06/16]  [ 2, 2, 25/06/16]  

Any idea how to achieve this?

CSS - Unable to align images horizontally in 3s

Posted: 25 Jun 2016 06:41 AM PDT

Trying to align images/contacts horizontally in 3 (wide) x however many (long). Currently the appearance is step like and not horizontal.

Used the below code and switched out float: left; for display: inline-block; and some others, the structure remains as it 'step like'.

Any ideas how to correct this or if there is something very awry in the code?

index.html.erb

<html>    <head></head>  <style>    body {margin:20px; }    .polaroid {      float: left;      background-color: white;      box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);      margin: 5px;      border: 1px solid #ccc;      width: 180px;  }    .polaroid:hover {      border: 1px solid #777;  }    .container {      width: auto;      height: auto;      text-align: left;      padding: 10px 27px;  }    .work {      width: 100;      height: 100;      min-width: 100%;      min-height: 100%;      border-radius: 50%;      overflow: hidden;      padding:5px 4px;  }    </style>    <body>    <div>  <%if user_signed_in? %>    <%= link_to 'Log out', destroy_user_session_path, method: :delete %>  <%end%>  </div>    <% if @contacts.any? %>    <% @contacts.each do |contact| %>  <div class="polaroid">    <div class="container">    <%= link_to image_tag(contact.image.url(:thumb), :class=>"work" ), contact_path(contact) %>    <h3><%=contact.firstname%> <%=contact.surname%></h3>    <%=contact.email%><br />    <%=contact.phone%>  </div>  </div>    <br />    <br />    <%end%>  <%else%>    No contacts yet!  <%end%>    <br />  <br />    <%= link_to 'Add a contact', new_contact_path%>    </body>    </html>  

Rails Sass _settings issue

Posted: 25 Jun 2016 05:20 AM PDT

I have installed foundation-rails gem according to its documentation and I am trying to setup mu own variables for certain styles for separate parts of my application in _settings.scss, however when I declare a variable it throws an error 'Udnefined variable'.

This is my application.scss:

 *= require_tree .   *= require_self   *= require foundation_and_overrides   *= require navbar   *= require topbar   */  

These are my variables in _settings.scss: //RF colors

$dark-blue: #2b3e51; $deep-blue: #394b5d;

//Side navigation colors

$left-menu-bg-color: $dark-blue;  $left-menu-border-color: #6F7E85;  $left-menu-main-nav-bg-color: $deep-blue;  $left-menu-width: 275px;  $top-bar-z-index: 99;  

And it says Undefined variable: "$left-menu-bg-color".

The documentation says that _settings.scss will be automatically included. Am I missing something?

How to make post request call to Facebook Graph Api using Httparty in rails?

Posted: 25 Jun 2016 05:18 AM PDT

I am trying to build a bot for Facebook Messenger. I have to post request call to Facebook Graph Api. Sample code they gave is in node.js. I am using rails as my backend.

Sample Code

request({      uri: 'https://graph.facebook.com/v2.6/me/messages',      qs: { access_token: PAGE_ACCESS_TOKEN },      method: 'POST',      json: messageData  });  

I am using Httparty gem for making post requests.Problem is i don't know what is qs in request. So how should i give qs information to facebook ? Help me to convert above sample code into rails code.

Ruby task uses 97 %CPU

Posted: 25 Jun 2016 06:43 AM PDT

My ruby application uses about 97 %CPU which eventually gets killed. The program is reading files from the folder and if a file name exists in the database, it skips it and checks another file. While executing this procedure, application usually gets killed.

COMMAND      %CPU  ruby         96.5  

Even if I insert almost all files and try to lunch an application again (because it was killed), system tends to kill it even sooner. How can I decrease the %CPU?

task :process_data, [:data_directory] => :environment do |_task, args|      # add data to a database      saver = CsvToSqlSaver.new      saver.fill_files_names        Dir.foreach(args.data_directory) do |filename|        # if not present in records already we read it        Base.logger.info "> Found #{filename}."        next if saver.files_names.to_s.include?(filename) ||                !filename.include?('csv')        Base.logger.info "> Reading #{filename}."          begin          saver.generate_db_rows_from_csv_file(args.data_directory, filename)        # handle Malformed .csv exception        rescue CSV::ArgumentError, CSV::MalformedCSVError => e         Base.logger.info e.message          next        end # we continue csv file loop?          unless integrator.insert_data_to_database         Base.logger.info '> No new data saved.'        end      end  end  

This is fill_files_names:

 def fill_files_names        @files_names = []        files_names = MyFilesTable.select(:filename).distinct        files_names.each do |row|          @files_names.push(row[:filename])        end   end  

This is Base:

class Base      class << self        attr_accessor :logger      end      @logger ||= Logger.new(STDERR)  end  

This is generate_db_rows_from_csv_file

def generate_db_rows_from_csv_file(directory, filename)        @incoming_data = []          CSV.foreach("#{directory}/#{filename}",                    headers: true, quote_char: "\x00") do |csv_record|          # if invalid record, go further          next if record_invalid?(csv_record)            generate_row_in_the_database(csv_record, filename)        end  end  

Ruby on rails - gmaps4rails - passing marker data. Maximum call stack size exceeded

Posted: 25 Jun 2016 05:48 AM PDT

Hello I'm using paloma gem to separate some of my javascript. When trying to add a marker to the map I get the error Maximum call stack size exceeded from gmaps.

I am passing a variable (the marker coordinates) from my controller in json format to the js file, then adding that variable to an alert box (for testing) and the marker.

var arrCoo = this.params.hash;  alert(arrCoo);  markers = handler.addMarkers(arrCoo);  

(this.params.hash calls the variable sent from my controller). In this case, the alert box displays the coordinates eg:

[{"lat":57.4386015,"lng":16.6152354}]  

but I get the error Maximum call stack size exceeded and the marker and map don't display.


If I copy and paste the coordinates;

markers = handler.addMarkers([{"lat":57.4386015,"lng":16.6152354}]);  

then the marker shows on the map no problem.


In my case what is the difference between

markers = handler.addMarkers(arrCoo);  

and

markers = handler.addMarkers([{"lat":57.4386015,"lng":16.6152354}]);  

?? Why isn't the variable being seen the same way by the alert box and the marker attributes?

How to kill a daemon in Linux? [on hold]

Posted: 25 Jun 2016 05:02 AM PDT

Note: Before you mark this question as duplicate, please note that I've tried all the solutions that I could get online, but still I'm unable to resolve the problem.

I ran daemon through the following command:

rake resque:work QUEUE='*' &  

It returned me 13031. Now, I want to kill this daemon, and I've trying the following commands:

kill -9 13031  kill 13031  

Running both commands says: -bash: kill: (13031) - No such process, and now I'm stuck. I'm unable to figure out how to kill the daemon.

How to do redirect and give an error message after failed put

Posted: 25 Jun 2016 07:21 AM PDT

class FavoritePhoto < ActiveRecord::Base    belongs_to :user    belongs_to :photo    validates :user_id, uniqueness: {      scope: [:photo_id],     message: 'can only favorite an item once'     }  end    PhotosController  def favorite    @photo = Photo.find(params[:id])    if request.put?      current_user.favorites << @photo      redirect_to :back, notice: 'You successfully favorited this photo'    else request.delete?      current_user.favorites.delete(@photo)      redirect_to :back, notice: 'You successfully unfavorited this photo'    end  end    <%= link_to favorite_photo_path("#{photo.id}"), method: :put do %>    <span class="glyphicon glyphicon-heart"></span>  <% end %>    resources :photos do    match :favorite, on: :member, via: [:put, :delete]  end  

This works in preventing the User from favoriting the same photo more than once and the error message "User can only favorite an item once" shows up in my Heroku log, however, when they attempt to favorite a photo twice there is no redirect and message explaining to the User what has happened, it just times out at favorite_photo_path('#{photo.id}").

Make a generator of models inheriting from a pre-built model

Posted: 25 Jun 2016 06:25 AM PDT

I'm writing a little Ruby on Rails CMS, and I want to make a generator that would create models inheriting from the pre-built CMS data model. For example, I have a Entry model in my CMS, and I want to create a Post model that would be child of this model. This is the source code:

db/migrations/*create_mycms_entries.rb:

class CreateMyCmsEntries < ActiveRecord::Migration[5.0]    def change      create_table :my_cms_entries do |t|        t.string :type, index: true        t.string :title        t.string :slug, index: true        t.json :payload        t.integer :user_id, index: true        t.string :author_name          t.datetime :published_at        t.timestamps null: false      end    end  end  

entry.rb:

module MyCms    class Entry < ActiveRecord::Base      scope :published, -> { where('published_at <= ?', Time.zone.now) }        def self.content_attr(attr_name, attr_type = :string)        content_attributes[attr_name] = attr_type          define_method(attr_name) do          self.payload ||= {}          self.payload[attr_name.to_s]        end          define_method('#{attr_name}='.to_sym) do |value|          self.payload ||= {}          self.payload[attr_name.to_s] = value        end      end        def self.content_attributes        @content_attributes ||= {}      end    end  end  

and, at my blog side, post.rb:

class Post < MyCms::Entry    content_attrs :body, :text      # Rest of the stuff...  end  

I want the final command look something like this:

$ rails generate entry Post body:text  

But I'm not quite sure I know how to implement it.

Authorization tokens of users are saved as nil in session[:user_auth_token] and current_user helper method in application controller

Posted: 25 Jun 2016 02:55 AM PDT

I have been using session[:user_id] for my app and wanted to make it a little bit more secure so I generated auth_tokens for users and now i wanted to save session[:user_auth_token] in @current_user. When I am using user_id it is working fine but when I started using tokens it is returning nil. In my sessions controller I got

@user = User.find_by_email(params[:session][:email])      if @user && @user.authenticate(params[:session][:password])          if params[:remember_me]              session[:user_auth_token] = @user.auth_token              cookies.permanent[:auth_token] = @user.auth_token  

In my application controller I got

 @current_user ||= User.find_by_auth_token( session[:user_auth_token]) if session[:user_auth_token]  

I don't know what went wrong I just started learning rails.

Fail to build Nokogiri on Ubuntu ec2 via bundle

Posted: 25 Jun 2016 03:50 AM PDT

I know that there are many similar questions out there but none of their answers help me out with this. I used to install it without any problem before, after 6 months, I tried to bundle install again and it fail.

This is what i got, looks like the same as other people:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        /home/ubuntu/.rvm/rubies/ruby-2.2.1/bin/ruby -r ./siteconf20160625-23682-1ebh39x.rb extconf.rb --use-system-libraries  checking if the C compiler accepts ... *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:      --with-opt-dir      --without-opt-dir      --with-opt-include      --without-opt-include=${opt-dir}/include      --with-opt-lib      --without-opt-lib=${opt-dir}/lib      --with-make-prog      --without-make-prog      --srcdir=.      --curdir      --ruby=/home/ubuntu/.rvm/rubies/ruby-2.2.1/bin/$(RUBY_BASE_NAME)      --help      --clean  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)  You have to install development tools first.      from /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/mkmf.rb:571:in `block in try_compile'      from /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/mkmf.rb:522:in `with_werror'      from /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/mkmf.rb:571:in `try_compile'      from extconf.rb:80:in `nokogiri_try_compile'      from extconf.rb:87:in `block in add_cflags'      from /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/mkmf.rb:619:in `with_cflags'      from extconf.rb:86:in `add_cflags'      from extconf.rb:336:in `<main>'    extconf failed, exit code 1  

And the mkmf.log is:

"gcc -o conftest -I/home/ubuntu/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/x86_64-linux -I/home/ubuntu/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0/ruby/backward -I/home/ubuntu/.rvm/rubies/ruby-2.2.1/include/ruby-2.2.0 -I.     -O3 -fno-fast-math -ggdb3 -Wall -Wextra -Wno-unused-parameter -Wno-parentheses -Wno-long-long -Wno-missing-field-initializers -Wunused-variable -Wpointer-arith -Wwrite-strings -Wdeclaration-after-statement -Wimplicit-function-declaration -Wdeprecated-declarations -Wno-packed-bitfield-compat  -fPIC  conftest.c  -L. -L/home/ubuntu/.rvm/rubies/ruby-2.2.1/lib -Wl,-R/home/ubuntu/.rvm/rubies/ruby-2.2.1/lib -L. -fstack-protector -rdynamic -Wl,-export-dynamic     -Wl,-rpath,'/../lib' -Wl,-R'/../lib' -lruby  -lpthread -ldl -lcrypt -lm   -lc "  checked program was:  /* begin */  1: #include "ruby.h"  2:   3: int main(int argc, char **argv)  4: {  5:   return 0;  6: }  /* end */  

As I can see in the mkmf.log, it tells nothing about errors which is different to other questions I found on StackOverflow.

I installed all the dependencies that I know or mentioned on the Internet such as libxml2, libxml2-dev, libxslt-dev, ruby-dev, zlib1g-dev, liblzma-dev, libgmp-dev, patch.

I'm pretty much lost because I didn't do anything rather than trying to move all of my code and deployment assets to other directory. What I did exactly is that I registered new ESB and mounted it into the instance then I make a symlink to map my current path to that mount point.

Edit 1: I actually can install via gem gem install nokogiri -v '1.6.7' successfully. However bundle install fails.

Installed gem can't load from rails controller

Posted: 25 Jun 2016 01:34 AM PDT

I am dabbling with ruby on rails for the first time and have run into an issue while trying to load a gem from a controller.

To install the gem, I added it to (the top just below source) the Gemfile and ran bundle install. The gem is shown as installed and is in the Gemfile.lock. When installing, I was prompted for sudo password and a bundle show <gem> shows it in a system path (/var/lib/gems).

In the controller (in app/controllers/my_controller.rb), I am requiring it as follows:

class MyController < ApplicationController    def index       @somevar = dostuff    end      private      def dostuff       require 'some/lib'       return "foo"    end  end  

When I access the app, I get the following error:

cannot load such file -- some/lib

If i put the dostuff function into dostuff.rb in the project root and execute it with ruby dostuff.rb the gem is loaded fine.

Am I missing something about how gems are loaded in a rails environment or am I loading it up incorrectly?

I have read through these similar questions but they have not resolved the problem:

Rails can't find installed gem - is rbenv the only solution? would like to try get this working with a system gem. Does Rails load all installed gems? - im explicitly loading it but failing

payment gateway redirect to rails app throws ssl error

Posted: 25 Jun 2016 12:36 AM PDT

I am running rails 4 app with heroku and payumoney gateway. When customer makes payment using payment gateway then it redirects back to my web app. Few customers reported that they get "SSL error" during redirection to webapp after successful payment. What can be problem ?

I tried to reproduce, but it does not throw any error to me. Only once in a while some customer reports this error.

Getting notes through chapter or book in MySQL

Posted: 25 Jun 2016 05:16 AM PDT

I have three models:

notes, chapters and books

A note can either have a reference to a chapter (chapter_id) OR a reference to a book (book_id). Also, a chapter has a reference to a book (book_id).

Each chapter is referencing to a client (client_id) and each client is referencing to a user (user_id)

I want to find all the distinct notes that a specific user can read. Those are the chapter notes that belong to that user AND the book notes from those chapters.

Currently I have this query:

SELECT * FROM notes n   JOIN chapters c ON (c.id = n.chapter_id OR c.book_id = n.book_id)  JOIN clients cl ON (cl.id = c.client_id)  JOIN users u ON (u.id = cl.user_id)  WHERE u.id = my_user_id  

Since I want to run this on my model because I am paginating afterwards with kaminari, I am doing it like this (using Note model):

Note.joins(  %(  JOIN chapters c ON (c.id = n.chapter_id OR c.book_id = n.book_id)  JOIN clients cl ON (cl.id = c.client_id)  JOIN users u ON (u.id = cl.user_id)  ).  where("u.id = :id", id: given_user_id).  distinct  

This query runs pretty slow and I have a feeling this is due to do the OR in the JOIN clause (I have never seen or done that before), because I have tried with two separate queries (one to fetch the chapter notes and another one to fetch the book notes) and it runs faster.

I would like to know what is a proper way to solve this problem making sure that the results are paginatable.

How to run a long running job on Amazon EC2 instance in Rails?

Posted: 25 Jun 2016 03:35 AM PDT

I'm using resque gem, and I'm running the jobs through the following command:

rake resque:work QUEUE='*'  

But the problem is: As my SSH connection with remote server gets disconnected, or I close the SSH session window that is running the process rake resque:work QUEUE='*', it stops running the job.

I'd like to have a way in which the job will run independently: no need to remain connected with through SSH. Is there a way, or should I follow this procedure to accomplish what I require?

Pass parameter to the "create" action of my controller

Posted: 25 Jun 2016 12:08 AM PDT

My view has a form_for that when submitted gets directed to the "create" action of my controller. How do I pass an additional param (apart from the form contents which is passed implicitly)?

Different log files in Rails apps

Posted: 25 Jun 2016 04:25 AM PDT

I have a rails app and I want to be able to use different log files in each environment. So it won't be only development.log in development environment, there'll be multiple log files in it depending on the kinds of events that occur. How can I do that?

UDPATE: In, say, development environment the log file where everything written into is development.log. I want to have multiple log files more in development environment along with development.log.

How to open same modal with two different links with different behaviour?

Posted: 25 Jun 2016 12:13 AM PDT

I am having a modal that have two divs in it. Now i am willing to open the same modal with two different links.

Here is my modal:

  <!-- Modal -->  <div id="myModal" class="modal fade" role="dialog">    <div class="modal-dialog">        <!-- Modal content-->      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal">&times;</button>          <h4 class="modal-title">Modal Header</h4>        </div>        <div class="modal-body">          <%= link_to "Back","#",class: "btn btn-default",id: "Back-Link",style: "display:none"%>          <%= link_to "Next","#",class: "btn btn-default",id: "Next-Link"%>          <div id="One">            <p>Some text in the modal.</p>          </div>          <div id="Two" style="display:none">            <p>Modal Two.</p>          </div>        </div>        <div class="modal-footer">          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>        </div>      </div>      </div>  </div>  

Following are the links:

<%= link_to "Test","#", 'data-toggle': "modal", 'data-target': "#myModal"%>  <%= link_to "Test1","#", 'data-toggle': "modal", 'data-target': "#myModal"%>  

When I click on "Test" Link the modal should open with div id "One". And when i click on "Test1" the modal should open with div id "Two".

can anyone help me? Thank you in advance

Need help deploying Rails app to Openshift

Posted: 24 Jun 2016 10:58 PM PDT

I've created the Openshift app through the web console, installed the rhc gem, ran rhc setup in the terminal and then git clone <SSH URL>. The last step created a copy of my rails app in a folder in my rails app directory. Now how do I proceed from here? I've read a few articles on deploying rails to Openshift, but they're only confusing me even more (or maybe I'm just being thick). I need help on the following two things:

  • Deploy the app to Openshift
  • Once it's deployed, I want to change the storage directory such that images uploaded to the Openshift app stay permanently.

All answers are welcome! Thanks in advance!

How to setup a development environment for nodejs(MEAN) and ruby on rails in a single application?

Posted: 25 Jun 2016 04:15 AM PDT

I would like to create a social network, I added lot of features like chatting, admin access control, payment gateway(money transaction), file uploading(audio,video,and image etc) and more social features in my plan.So for that ruby on rails works very good in social features and nodejs work awesome in realtime stuffs and file uploading.

I searched a lot to set up a development environment for my project with both nodejs and ruby on rails or if it is possible to setup nodejs and stuffs inside the ruby on rails framework will good enough. Here's my questions :

  1. Is it possible to use nodejs inside the ruby on rails?
  2. How to do access control and authorization when i integrate both nodejs and rails?
  3. How to do chat system using this ?

Nodejs + ruby on rails + socket.io + Angularjs

Design an ec-commerce that product price can be added dynamically by optional sellable items

Posted: 24 Jun 2016 10:27 PM PDT

I'm developing an ec-commerce with Ruby on Rails.

I wonder know how could I design a product with variants sellable options.

For example, I have a room to rent. Therefore there are "Room" table and "RoomSKU" table

Room

  • name: STRING
  • guests: INT

RoomSKU

  • room_id: INT
  • date: DATE
  • price: INT

Each RoomSKU record should belongs_to a Room record.(Each Room has many room_skus)

What the tricky thing is, each room has many sellable products.

For example, an user can add breakfast($5) and pick-up service($100) for a room.

By the way, different room may has variants of breakfast price and pick-up price.

Here's my question.

  • How could I store the additional items information. I mean the variants breakfast and pick-up price.
  • How could I distinguish if user has bought those additional items, because they can only book a room without any extra-services.
  • LineItem table is common in EC commerce, How could I store the information for my use-case. eg: I book a W-HOTEL single room three days in a row, I only added breakfast service on the 2th day. How could we store this kind of information in a good way.

Every guide and information is welcomed

Many thanks

No comments:

Post a Comment