Saturday, July 30, 2016

How to get posts with votes between two numbers? - Rails | Fixed issues

How to get posts with votes between two numbers? - Rails | Fixed issues


How to get posts with votes between two numbers? - Rails

Posted: 30 Jul 2016 08:00 AM PDT

I tried this, but it didn't work, it returns all posts

Post.where(' -1 < cached_votes_score < 10')  

although

Post.where(' cached_votes_score < 10')  

works, any thoughts on this?

Nested resource under users, I want only the current_user to be able to access

Posted: 30 Jul 2016 07:43 AM PDT

I have the following under my routes.rb:

  resources :users do     resources :submitted_terms, only: [:index, :create, :show]     end  

I only want the current_user (the logged in user) to be able to see their own submitted_terms in terms of the index and show views. They shouldn't be able to see anybody else's index and show views and other people shouldn't be able to see theirs.

I think I know how to implement this but it feels sort of messy to me. Any thoughts?

Specificity issues with bootstrap

Posted: 30 Jul 2016 07:38 AM PDT

Why do I need !important for the margin:0 to show?

@import "bootstrap-sprockets";  @import "bootstrap";    .alert {    margin: 0 !important;  }  

and

 *= require_tree .   *= require_self  

Rails App behind Wordpress using fastcgi_intercept_errors

Posted: 30 Jul 2016 06:54 AM PDT

I'm starting a migration of a WordPress website to a rails application. The migration needs to be done gradually over the next few months, so I'll need to be able to run both sites in parallel. Using fastcgi_intercept_errors on a test environment I've managed to get any 404 errors returned by WordPress to forward on to the Rails application using the following configuration:

server {          listen 80 default_server;          listen [::]:80 default_server ipv6only=on;            server_name mydomain.com;          root         /var/www/html/wordpress;      index index.php index.html            error_page   500 502 503 504 404 @rails;        location / {          try_files $uri $uri/ /index.php?$args;          recursive_error_pages on;          error_page 404 = @rails;      }        location ~ \.php$ {                  fastcgi_pass unix:/run/php/php7.0-fpm.sock;                  fastcgi_index index.php;                  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;          fastcgi_intercept_errors on;                  include fastcgi_params;          error_page 404 = @rails;            }        location @rails{          passenger_enabled on;          passenger_user stephen;          rails_env development;          root /home/user/rails_app/app/public;      }  }  

The problem now comes when the rails app references any /assets links they always forward back into the rails app and always load the root location of the application.

Is there any way to fix this so that assets will also be treated as part of the rails application?

In Rails, Ajax sorting can't' keep up with User moving items around in my list

Posted: 30 Jul 2016 06:56 AM PDT

In my rails app I've made a list that allows the user to sort records by click/drag/dropping them to reorder. After each reorder I run the update action and pass along the old_index and new_index of the item moved and reorder the entire list. The application works as would expected as long as I don't reorder items at a very fast pace. My question is how can I improve the design I have to account for a quick paced sorting by the user and reflect those changes accurately? Also I'm trying to prevent the user from having to click a "Save" button -- however if it is necessary then I can implement that.

update action

      def update            if @list_item.present?              # update the modified item, and then update all items after that are affected            old_index = params[:old_rank].to_i            new_index = params[:sequence_rank].to_i              @list_item.update(sequence_rank: new_index) # update the moved item              # move element down and shift others up            if old_index < new_index              @list.list_items.where('sequence_rank <= (?) AND list_items.id \                <> (?) AND sequence_rank > (?)', new_index, @list_item.id, 0)                .each_with_index do |item,index|                item.update(sequence_rank: item.sequence_rank-1)              end            # move element up and shift elements down            else              @list.list_items.where('sequence_rank >= (?) AND list_items.id \               <> (?) AND sequence_rank < (?)', new_index, @list_item.id, old_index+1)               .each_with_index do |item,index|                item.update(sequence_rank: item.sequence_rank+1)              end            end            end            render nothing: true          end  

Also I'm using the following gem: https://github.com/scttdavs/sortable-rails

uninitialized constant ActiveModel::Observing (NameError)

Posted: 30 Jul 2016 06:44 AM PDT

I have developed a web application using ruby on rails. I have upgraded my rails version from 3.2 to 4.0 and I am getting the below error while starting my server.

Error :

/home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:11:in <module:Config>': uninitialized constant ActiveModel::Observing (NameError) from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:8:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:5:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid.rb:21:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:76:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:76:inblock (2 levels) in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:74:in each' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:74:inblock in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:63:in each' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:63:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler.rb:132:in require' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config/application.rb:88:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config/environment.rb:6:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:3:inblock in ' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:55:in instance_eval' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:55:ininitialize' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:in new' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:49:in eval' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:49:innew_from_string' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:40:in parse_file' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:277:inbuild_app_and_options_from_config' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:199:in app' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:314:inwrapped_app' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:250:in start' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:141:instart' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/bin/rackup:4:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/bin/rackup:23:inload' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/bin/rackup:23:in <main>' /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/ruby2.1.x/lib/ruby/site_ruby/2.1.0/amazon/brazil/ruby.rb:98:inexec_build_script': Command exited with status 1!! (RuntimeError) from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:61:in block in <main>' from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:48:ineach' from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:48:in `'

Can any one help me resolve this issue?

scroll bar with Lazy Highcharts

Posted: 30 Jul 2016 05:30 AM PDT

Hi I am relatively new to rails and I am trying to implement a horizontal scrollbar using the lazy highcharts gem. So far I am having trouble getting the scrollbar to work, any suggestions on what I am doing wrong/leaving out?

Controller:

@logsChart = LazyHighCharts::HighChart.new('graph') do |f|   f.series(:name=>'Session 2',:data=> [0, 20, 3, 5, 4, 10, 12 ])   f.series(:name=>'Session 1',:data=>[1, 3, 4, 3, 3, 5,4,-46,2,3,2,1,5,6,7,3,2,4,3,5,7] )    f.title({ :text=>"Load per Session"})   f.xAxis( min: 0,            max:12,           labels: {overflow: 'justify'})   f.scrollbar(enabled: true)   f.options[:chart][:defaultSeriesType] = "column"   f.plot_options({:column=>{:stacking=>"percent"}})  end  

View:

<%= high_chart("my_id", @logsChart) %>  

Gemfile:

gem 'lazy_high_charts', '1.5.0'  gem 'highstock-rails'  

application.js:

//= require highcharts  //= require exporting  //= require highcharts/highcharts  //= require highcharts/highcharts-more  //= require highcharts/highstock  

How do I display all attributes from a rails select statement?

Posted: 30 Jul 2016 06:36 AM PDT

Please would it be possible to know how to display the :user_id, :player_id and :amount attributes together in a hash from the below code?

At the moment the array created returns player_id as the key and amount as the value {1695=>100, 1714=>200} whereas I need something like {1695=>{:user_id,100}?

The code in the controller is as follows:

@duplicates = Bid.select(:player_id, :user_id, :amount).group(:player_id).having("count(*) > 1").maximum(:amount)  

The code in the view:

<div class="col-sm-3" style="background-color:white;">        <%= @duplicates %><br>    </div>  

Issue running rake task on azure server (via cloud66)

Posted: 30 Jul 2016 07:24 AM PDT

So i've got a cloud66 server (azure) running my web app

I'm trying to get the rake task to run on my webserver to populate my database (it runs fine locally)

Heres the error log im getting back

W, [2016-07-29T23:22:55.602769 #44674] WARN -- : Failed creating logger for file /var/deploy/appname/web_head/releases/20160729211819/log/newrelic_agent.log, using standard out for logging.    W, [2016-07-29T23:22:55.610222 #44674] WARN -- : Errno::EACCES: Permission denied @ rb_sysopen - /var/deploy/appname/web_head/releases/20160729211819/log/newrelic_agent.log    D, [2016-07-29T23:22:55.610373 #44674] DEBUG -- : Debugging backtrace:    /usr/local/lib/ruby/2.2.0/open-uri.rb:36:in `initialize'    /usr/local/lib/ruby/2.2.0/open-uri.rb:36:in `open'    /usr/local/lib/ruby/2.2.0/open-uri.rb:36:in `open'    /usr/local/lib/ruby/2.2.0/logger.rb:628:in `open_logfile'    /usr/local/lib/ruby/2.2.0/logger.rb:584:in `initialize'    /usr/local/lib/ruby/2.2.0/logger.rb:318:in `new'    /usr/local/lib/ruby/2.2.0/logger.rb:318:in `initialize'  

Any ideas why this is failing?

How can i take a cut/commission in paypal?

Posted: 30 Jul 2016 05:05 AM PDT

how can i take a cut/commission in paypal after user has paid amount and before receiver has got amount.

In my application I allow sellers to give some service to customers. When a customer pays $100 to seller then I need to cut 12.5% as commission.

How can I do that in Paypal. My Application is in rails.

Brakeman Error - Unescaped model attribute near

Posted: 30 Jul 2016 07:08 AM PDT

I am getting a lot error as follows

Unescaped model attribute near line 20: show_errors(Objective.new(objective_params), :name)  

Expanded View

This is my code

module ApplicationHelper    # Error Helper for Form    def show_errors(object, field_name)      if object.errors.any? && object.errors.messages[field_name][0].present?        "<label class='text-error'>" + object.errors.messages[field_name][0] + "</label>"      else        return ""      end    end    end  

getting Missing Template error while creating a new user

Posted: 30 Jul 2016 04:50 AM PDT

Missing template admin/citizens/create, admin/application/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :haml, :jbuilder, :rabl]}. Searched in: * "/Users/aa/Sites/Active Shehri/activeshehri-mongo/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/wiselinks-1.2.1/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/rails_admin-0.6.6/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/kaminari-0.16.1/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/devise_invitable-1.5.5/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/twitter-bootstrap-rails-3.2.2/app/views" * "/Users/aa/.rvm/gems/ruby-2.2.2@activeshehri/gems/devise-3.4.1/app/views"

.....here is the code

= form_for [:admin, @user] do |f|    .row      .col-lg-6        .panel          .panel-heading Edit Landmark          .panel-body            .form-group              = f.label :first_name              = f.text_field :first_name, class: 'form-control'            .form-group              = f.label :last_name              = f.text_field :last_name, class: 'form-control'            .form-group              = f.label :email              = f.text_field :email, class: 'form-control'            .form-group              = f.label :gender              = f.text_field :gender, :class => 'form-control'            .form-group              = f.label :contact_no              = f.text_field :contact_no, :class => 'form-control'            .form-group              = f.label :address              = f.text_field :address, class: 'form-control'          = f.submit 'Save', class: 'btn btn-primary btn-submit btn-lg pull-right'          = link_to "Back", admin_home_user_panel_path, class: 'btn btn-primary btn-submit btn-lg pull-left'  

How can I use the normal radio buttons in react?

Posted: 30 Jul 2016 03:53 AM PDT

I am developing a webapp which uses materializecss, react along with ruby on rails. I'd like to know how I can use the radio buttons such that it can be rendered.

    class Radio extends React.Component {          constructor(props) {    super(props);      this.state = {      }      this.setNewNumber = this.setNewNumber.bind(this)  };     setNewNumber(event)   {      this.setState({val : event.target.value})    }    render() {    return (         <div>          <input type="radio" name="gender" value="male" onChange={this.setNewNumber}/> Male<br/>          <input type="radio" name="gender" value="female"onChange={this.setNewNumber}/> Female<br/>          <input type="radio" name="gender" value="other"onChange={this.setNewNumber}/> Other          <p>Enter {this.state.val}</p>       </div>       );    }  }  

Rails 4 - 2 word model names

Posted: 30 Jul 2016 03:43 AM PDT

I'm using rails 4 with pundit and with statesman.

In each case, my pundit policy and my statesman model files don't work where the model name attached to them has two words.

For example, I have a model called organisation_request.rb

I have setup a pundit OrganisationRequestPolicy (in the same way I have set up every other pundit policy that applies to a model with a single word model name) and a state_tranistions file OrganisationRequestTransition (organisation_request_transition).

The pundit/statesman files don't work. The only difference I can see is that the model name has two words.

Is there a special convention for working with two word model names with these gems?

Capistrano deployed the app but its not opening in browser

Posted: 30 Jul 2016 02:56 AM PDT

I've a rails app that I'm trying to upload to a Digital Ocean (DO)'s droplet using capistrano, nginx and puma. I followed the tutorial in this link https://www.digitalocean.com/community/tutorials/deploying-a-rails-app-on-ubuntu-14-04-with-capistrano-nginx-and-puma and got the deployment part of the app to work. I didn't change much in my configuration files else than app name or changing server name in nginx.conf file to my droplet's ip. On deployment puma server starts. The trace messages are following:

Execute puma:start  04:35 puma:start        using conf file /home/root/apps/lixerr/shared/puma.rb        01 /usr/local/rvm/bin/rvm default do bundle exec puma -C /home/root/apps/lixerr/shared/puma.rb --daemon        01 RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does that too,        01        01 you can ignore these warnings with 'rvm rvmrc warning ignore /home/root/apps/lixerr/current/Gemfile'.        01        01 To ignore the warning for all files run 'rvm rvmrc warning ignore allGemfiles'.        01        01         01        01 Puma starting in single mode...        01        01 * Version 3.6.0 (ruby 2.3.0-p0), codename: Sleepy Sunday Serenity        01        01 * Min threads: 4, max threads: 16        01        01 * Environment: production        01        01 * Daemonizing...        01      ✔ 01 root@138.68.3.74 1.441s  

I checked the log files on my droplet, puma starts w/o showing any error messages. Moreever I also symlinked the nginx.conf to the sites-enabled directory and sites-available directory using:

sudo ln -nfs "/home/deploy/apps/appname/current/config/nginx.conf" "/etc/nginx/sites-enabled/appname"  

which they have mentioned at the end of the tutorial. Nginx is installed on droplet and I did not forget restarting it after creating the link. Still whenever I try to connect to droplet using its ip at http://138.68.3.74/ I get the following error in chrome:

This site can't be reached    138.68.3.74 refused to connect.  ERR_CONNECTION_REFUSED  

I've been working on it since last day and can't get it to work. I've no idea what am I missing.


EDIT 1: The log files of nginx in /var/log/nginx directory show nothing at all.

Checkbox "NoMethodError" in rails

Posted: 30 Jul 2016 03:27 AM PDT

I'm writing a CMS and I faced a problem while making a role management for users. I have a boolean field :admin in my User model, and I've made a checkbox in my form to set created user as an administrator. Here is the users_controller:

def create    @user = User.create(user_params)    respond_to do |format|      if @user.save        format.html { redirect_to users_path }        format.json { head :no_content }      else        format.html { render :new }        format.json { render @user.errors, status: :unprocessable_entity }      end    end  end    def edit  end    def update    respond_to do |format|      if @user.update(user_params)        format.html { redirect_to users_path }        format.json { head :no_content }      else        format.html { render :edit }        format.json { render @user.errors, status: :unprocessable_entity }      end    end  end  

and this is my form :

<%= form_for @user do |f| %>    # Here go fields for username, email and password    <p>      <%= f.label "Set as administrator" %> <br />      <%= f.hidden_field :admin, '' %>       # I also tried with <%= f.hidden_field :admin, false %>      <%= f.check_box :admin, checked = true %>       # Or <%= f.check_box :admin, data: { switch: true } %>    </p>  <% end %>  

But any of these options returns me the following:

NoMethodError in Multiflora::Users#edit    undefined method `merge' for "":String  

What have I done wrong?

Rails 4 - Mini_Magick doesn't work with images - don't see any resized pictures

Posted: 30 Jul 2016 05:33 AM PDT

I'm using Rails 4 + Carrierwave + Mini_Magick for image processing.

In my catalog all thumbnails are not displayed - "version :thumb" don't work.

In rails server log I see many routing errors like that:

Started GET "/uploads/item_image/image/57/thumb_testfile2.jpg" for ::1 at 2016-07-30 12:01:56 +0300  ActionController::RoutingError (No route matches [GET] "/uploads/item_image/image/57/thumb_testfile2.jpg"):  


When I change view partial from

...  = image_tag item.item_images.first.image.thumb.url  

to

...  = image_tag item.item_images.first.image.url  

fullsize images appear for all items!


How to fix that?

UPDATE

Mini_magick works only for pictures uploaded through form_for. When I upload items through my import-script - thumbs not generate

code from my import script:

folder="tmp/c_pics/"  path=folder + filename  new_image=ItemImage.new                           new_image.image = Rails.root.join(path).open  new_image.save!  curr_item.item_images << new_image  curr_item.save!  

I think that import script doesn't create thumbs during upload


Rails 4.2.6 + carrierwave 0.11.2 + mini_magick 4.5.1


Models

models/item.rb

class Item < ActiveRecord::Base      ...      has_many  :item_images      accepts_nested_attributes_for :item_images, :allow_destroy => true, reject_if: proc { |attributes| attributes[:image].blank? }  end  

models/item_image.rb

class ItemImage < ActiveRecord::Base      mount_uploader  :image, ImageUploader       belongs_to      :item  end  

Views

views/items/index.html.haml

%h1       All items  .items-list      = render "items_list"  %p      = link_to "Create new item", new_item_path(@item)  

views/items/_item_block.html.haml

%li      .pic          = image_tag item.item_images.first.image.thumb.url      .item_attr.name          = link_to item.name, item      .item_attr.price          price:          = item.price        .edit_control          = link_to "Edit Item", edit_item_path(item)  

views/items/_items_list.html.haml

%ul      - @items.each do |i|          = render "item_block", item: i  

Uploader

uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base          include CarrierWave::MiniMagick          storage :file          def store_dir          "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"        end          version :thumb do          process :resize_to_fit => [236, 236]        end          def extension_white_list          %w(jpg jpeg gif png)        end    end  

Database

db/schema.rb

...    create_table "items", force: :cascade do |t|    t.datetime "created_at", null: false    t.datetime "updated_at", null: false    t.string   "name"    t.string   "model"    t.decimal  "price",      precision: 8, scale: 2  end    create_table "item_images", force: :cascade do |t|    t.string   "image"    t.string   "item_id"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end    ...  

Gemfile

...  gem 'carrierwave'  gem "mini_magick"  gem 'rmagick'  

Console

results of "convert -version" command:

MacbookPro:eshop admin$ convert -version  Version: ImageMagick 6.9.3-7 Q16 x86_64 2016-03-27 http://www.imagemagick.org  Copyright: Copyright (C) 1999-2016 ImageMagick Studio LLC  License: http://www.imagemagick.org/script/license.php  Features: Cipher DPC Modules   Delegates (built-in): bzlib freetype jng jpeg ltdl lzma png tiff xml zlib  

results of "bundle show mini_magick" command:

MacbookPro:eshop admin$ bundle show mini_magick  /Users/aku/.rvm/gems/ruby-2.2.1/gems/mini_magick-4.5.1  

results of "bundle show rmagick" command:

MacbookPro:eshop admin$ bundle show rmagick  /Users/aku/.rvm/gems/ruby-2.2.1/gems/rmagick-2.15.4  

RoutingError (console - rails s)

Started GET "/uploads/item_image/image/57/thumb_testfile2.jpg" for ::1 at 2016-07-30 12:01:56 +0300    ActionController::RoutingError (No route matches [GET] "/uploads/item_image/image/57/thumb_testfile2.jpg"):  actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'  web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'  web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'  web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'  railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app'  railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged'  railties (4.2.6) lib/rails/rack/logger.rb:20:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call'  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'  rack (1.6.4) lib/rack/runtime.rb:18:in `call'  activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  rack (1.6.4) lib/rack/lock.rb:17:in `call'  actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call'  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'  railties (4.2.6) lib/rails/engine.rb:518:in `call'  railties (4.2.6) lib/rails/application.rb:165:in `call'  rack (1.6.4) lib/rack/lock.rb:17:in `call'  rack (1.6.4) lib/rack/content_length.rb:15:in `call'  rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'  /Users/admin/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'  /Users/admin/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'  /Users/admin/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'  

Routing Error - No route matches [POST] "/xvaziris/125/hide"

Posted: 30 Jul 2016 03:32 AM PDT

Actually I wanted to hide the records on button click temporarily with carrying forward the running balance.

Please refer the screen-shot for better understanding as shown below;

image.png

When I clicked the "Hide" button, I keep running into the following error:

No route matches [POST] "/xvaziris/125/hide"

Please refer the screen-shot for better understanding as shown below;

screenshot.png

As I mentioned the method: :get in my partial but still it gives me the post routing error.

I tried running rake routes and I can see that the route exists:

C:\Users\pos1\Desktop\offorgs>bundle exec rake routes  DL is deprecated, please use Fiddle  DL is deprecated, please use Fiddle               Prefix Verb   URI Pattern                    Controller#Action                 root GET    /                              xvaziris#index         **hide_xvaziri GET    /xvaziris/:id/hide(.:format)   xvaziris#hide**             xvaziris GET    /xvaziris(.:format)            xvaziris#index                      POST   /xvaziris(.:format)            xvaziris#create          new_xvaziri GET    /xvaziris/new(.:format)        xvaziris#new         edit_xvaziri GET    /xvaziris/:id/edit(.:format)   xvaziris#edit              xvaziri GET    /xvaziris/:id(.:format)        xvaziris#show                      PATCH  /xvaziris/:id(.:format)        xvaziris#update                      PUT    /xvaziris/:id(.:format)        xvaziris#update                      DELETE /xvaziris/:id(.:format)        xvaziris#destroy      import_xvaziris POST   /xvaziris/import(.:format)     xvaziris#import                      GET    /xvaziris(.:format)            xvaziris#index                      POST   /xvaziris(.:format)            xvaziris#create                      GET    /xvaziris/new(.:format)        xvaziris#new                      GET    /xvaziris/:id/edit(.:format)   xvaziris#edit                      GET    /xvaziris/:id(.:format)        xvaziris#show                      PATCH  /xvaziris/:id(.:format)        xvaziris#update                      PUT    /xvaziris/:id(.:format)        xvaziris#update                      DELETE /xvaziris/:id(.:format)        xvaziris#destroy  xvaziri_resetfilter GET    /xvaziri/resetfilter(.:format) xvaziris#reset_filter  

routes.rb

Rails.application.routes.draw do          root 'xvaziris#index'        resources :xvaziris do          member do              get :hide          end      end        resources :xvaziris do           collection { post :import }      end          get '/xvaziri/resetfilter', to: 'xvaziris#reset_filter'    end  

xvaziris_controller.rb

class XvazirisController < ApplicationController      before_action :set_xvaziri, only: [:show, :edit, :update, :destroy]          def index          @xvaziris = Xvaziri.find_by hidden: false          @xvaziris = Xvaziri.search(params[:search])            respond_to do |format|              format.js              format.html           end       end        def import          Xvaziri.import(params[:file])          redirect_to xvaziris_url, notice: "Xvaziris imported."      end        def show      end        def new          @xvaziri = Xvaziri.new      end        def create          @xvaziri = Xvaziri.new(xvaziri)          if              @xvaziri.save              flash[:notice] = 'Xvaziri Created'              redirect_to @xvaziri          else              render 'new'          end      end        def edit      end        def update          if @xvaziri.update(xvaziri)              flash[:notice] = 'Xvaziri Updated'              redirect_to @xvaziri          else              render 'edit'          end        end        def destroy          @xvaziri.destroy          flash[:notice] = 'Xvaziri was successfully destroyed.'          redirect_to xvaziris_url          end        def hide          @xvaziri = Xvaziri.find(params[:id])          @xvaziri.hidden = true          flash[:notice] = 'Xvaziri was successfully hidden.'          redirect_to xvaziris_url          end        def reset_filter          xvaziris = Xvaziri.all          xvaziris.each do |xvaziri|              xvaziri.hidden = false          end          redirect_to xvaziris_url      end        private      # Use callbacks to share common setup or constraints between actions.      def set_xvaziri          @xvaziri = Xvaziri.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def xvaziri          params.require(:xvaziri).permit(:date, :description, :amount, :discount, :paid)      end    end  

index.html.erb

<div class="row">            <div class="col-md-10 col-md-offset-1">                <div class="table-responsive myTable">                    <table id = "kola" class="table listing text-center">                      <thead>                      <tr class="tr-head">                          <td>Description</td>                          <td>Amount</td>                          <td>Discount</td>                          <td>Paid</td>                          <td>Balance</td>                          <td>Button</td>                      </tr>                      </thead>                        <tbody>                                        <%= render @xvaziris %>                      </tbody>                      </table>                  </div>              </div>          </div>      <br>  <br>   <br>     <%= link_to "Show all", xvaziri_resetfilter_path %>  

_xvaziri.html.erb

<tr   class="tr-<%= cycle('odd', 'even') %>">        <td class="col-3"><%= span_with_possibly_red_color xvaziri.description %></td>          <td class="col-1"><%= number_with_precision(xvaziri.amount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.discount, :delimiter => ",", :precision => 2) %></td>        <td class="col-1 neg"><%= number_with_precision(xvaziri.paid, :delimiter => ",", :precision => 2) %></td>          <% @balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>        <% color = @balance >= 0 ? "pos" : "neg" %>        <td class="col-1 <%= color %>"><%= number_with_precision(@balance.abs, :delimiter => ",", :precision => 2) %></td>        <td class="col-1"><%= button_to "Hide", controller: "xvaziris", action: "hide", id: xvaziri, method: :get %></td>    </tr>  

Any suggestions are most welcome.

Thank you in advance.

searchkick's autocomplete does not work on my iphone safari?

Posted: 30 Jul 2016 02:20 AM PDT

I've implemented elasticsearch/searchkick on my rails app and it works both in development and production on desktop browsers. But I noticed that the autocomplete does not work on safari on my phone. I reviewed the searchkick's docs and I've seen nothing about this issue. Anyone?

When I click on accept an invitation, I immediately get redirected

Posted: 30 Jul 2016 01:57 AM PDT

In my invitation controller I have this where I want to customize saving a user when they accept an invitation:

class InvitationsController < Devise::InvitationsController    before_filter :configure_permitted_parameters, if: :devise_controller?      private      def accept_resource      resource_class.accept_invitation!(update_resource_params)    end      def configure_permitted_parameters      #......  

When I click on accept an invitation, I immediately get redirected, it doesn't show me the "enter your new password" page:

Processing by InvitationsController#edit as   Redirected to http://localhost:3000/  Filter chain halted as :resource_from_invitation_token rendered or redirected  Completed 302 Found in 0ms (ActiveRecord: 0.0ms)  

I've tried to set this:

   config.allow_insecure_token_lookup = true  

but it throwed an exception at startup.

devise 4.2  devise_invitable   

How to create scaffold with many field relation from various two tables

Posted: 30 Jul 2016 04:43 AM PDT

I want to create a scaffold for table with below references. Heretransport_supervisor_id,manager_id,loading_supervisor_idthese things comes under user table references

  load_type_id (belongs_to load_type)    load_pick_from_date (date)    load_pick_to_date (date)    price (decimal presision 9,2)    transport_supervisor_id (belongs_to user)    manager_id (belongs_to user)    loading_supervisor_id (belongs_to user)    company_id (belongs_to company)  

How can i create like this? i want to create this rails g scaffolding command itself only.

Rendering another controllers action as a partial from another view in Rails

Posted: 30 Jul 2016 07:28 AM PDT

I am trying to render a partial (e.g in controllerA) from another controller (e.g controllerB), in my view. The partial is rendering correctly with static content but when trying to access an instance variable, it fails. The instance variable is instantiated by an action in controllerB but this action is never called when simply rendering the partial.

Is there a way to call an action before rendering the partial?

PG::InsufficientPrivilege: ERROR: must be owner of database

Posted: 30 Jul 2016 01:36 AM PDT

Good morning!

Faced with the problem that when you run the tests, swears that the error with the database owner, but just before given privileges to the user at the database with the tests, please tell me where to dig.

The test itself takes place, but before it pops up this error, username and database match the settings in the database.yml

I found a similar article, but I have another error, and this decision does not apply: ActiveRecord::StatementInvalid: PG::Error: ERROR: must be owner of database

Error Code: PG :: InsufficientPrivilege: ERROR: must be owner of database test

System:

Rails: 5.0.0

Ruby: 2.3.1

PSQL: 9.5.3

String.gsub in Ruby messing up the replacement?

Posted: 30 Jul 2016 04:22 AM PDT

This is a very unusual issue for me coming from JS background. I'm simply trying to replace a part of the page with external content on the fly.

Here is the source.html:

<!DOCTYPE html>  <html>    <head>      <%= foobar %>    </head>    <body>      This is body    </body>  </html>  

And a replacement string inject.js:

var REGEXP  = /^\'$/i; var foo = 1;  

Finally a ruby code that spits the output file by combining both.

pageContent = File.read('./source.html')  jsContent = File.read('./inject.js');  output = pageContent.gsub("<%= foobar %>", jsContent)  File.open('./dest.html', "w+") do |f|    f.write(output)  end  

However, I get the messed up dest.html which is happening because of \' in inject.js.

<!DOCTYPE html>  <html>    <head>      var REGEXP  = /^    </head>    <body>      This is body    </body>  </html>$/i; var foo = 1;    </head>    <body>      This is body    </body>  </html>  

How do I get rid of this naive issue?

Rails will_paginate with named scope for associations > 0

Posted: 30 Jul 2016 01:30 AM PDT

Similar to will_paginate with named_scopes but not getting an error - rather unexpected results. Rails version 4.

If I have a scope in a Foo model (where a user has_many: foos) - models/foo.rb:

belongs_to :user  scope :hasCars, -> { joins(:cars) }  

And now try use the scope with will_paginate (in the controller):

@foos = auser.foos.hasCars.paginate(:page=>1,:per_page=>20)  

Then the view duplicates each foo by the number of cars they have in the :through ownership association - so for foo 1 - 4 of a given user:

foo1.cars.size # =>1  foo2.cars.size # =>4  foo3.cars.size # =>0  foo4.cars.size # =>2  

View:

foo1  foo2  foo2  foo2  foo2  foo4  foo4  

Works as expected without the paginate and paginate works fine without the scope.

The association of Foo to cars is :through => :ownership. I guess it's to do with the way the scope is created using a join and how that join is passed to will_paginate. This is the query I see in the logs:

SELECT "".* FROM "foos" INNER JOIN "ownership" ON "ownership"."foo_id" = "foos"."id" INNER JOIN "cars" ON "car"."id" = "ownership"."car_id" WHERE "foos"."user_id" = ? [["user_id", 1]]

This should return the correct number of rows. But then for each car owned by Foo, I see a query cars from cars where foo_id = X being duplicated, am guessing from a query generated by will_paginate

Is there a better way to create the scope? Or should will_paginate be set up differently? Or could this be a will_paginate bug?

I have tried using joins(:ownership) too in the scope - same behaviour.

Make a copy of tenant in apartment gem

Posted: 30 Jul 2016 01:21 AM PDT

I am using apartment gem with PostgreSQL and I need to make a copy of already existing tenant with data. One way which I can think of one way is to collect all data from the tenant and then switch tenant and start creating record below is a small demonstration.models are the list of models to be copied over.

Apartment::Tenant.switch!('destination')  models.each do |modal|      eval("@#{modal.downcase} = #{modal}.all.collect{ |p| p.to_dh }")      end  Apartment::Tenant.switch!('target')  models.each do |modal|      eval("@#{modal.downcase}.each{ |p| #{modal}.create(p[:attributes], :without_protection => true) rescue p[:id]}")  end  models.each do |modal|  ActiveRecord::Base.connection.reset_pk_sequence!(eval("#{modal}.table_name"))         end  

Any help will be greatly appreciated.

not able to configure godaddy dedicated server

Posted: 30 Jul 2016 01:15 AM PDT

Hi I brought new godaddy dedicated server and changed named server and most of the settings. Installed nginx and unicorn server and my app data reside in /var/www/epiphanity location. But still my rails app is not working, nginx server is running properly

See the below screenshot what it shows. Struggling with this from last two days. I followed this tutorial, any help on this please.

How To Set Up Nginx Server Blocks on CentOS 7

enter image description here

Struggling to optimize rails WHERE NOT IN query in Rails

Posted: 30 Jul 2016 06:38 AM PDT

Here's the query as it is in rails:

User.limit(20).    where.not(id: to_skip, number_of_photos: 0).    where(age: @user.seeking_age_min..@user.seeking_age_max).    tagged_with(@user.seeking_traits, on: :trait, any: true).    tagged_with(@user.seeking_gender, on: :trait, any: true).ids  

And here's the output of EXPLAIN ANALYZE. Note the id <> ALL(...) part is shortened. There are around 10K ids in it.

Limit  (cost=23.32..5331.16 rows=20 width=1698) (actual time=2237.871..2243.709 rows=20 loops=1)    ->  Nested Loop Semi Join  (cost=23.32..875817.48 rows=3300 width=1698) (actual time=2237.870..2243.701 rows=20 loops=1)          ->  Merge Semi Join  (cost=22.89..857813.95 rows=8311 width=1702) (actual time=463.757..2220.691 rows=1351 loops=1)                Merge Cond: (users.id = users_trait_taggings_356a192.taggable_id)                ->  Index Scan using users_pkey on users  (cost=0.29..834951.51 rows=37655 width=1698) (actual time=455.122..2199.322 rows=7866 loops=1)                      Index Cond: (id IS NOT NULL)                      Filter: ((number_of_photos <> 0) AND (age >= 18) AND (age <= 99) AND (id <> ALL ('{7066,7065,...,15624,23254}'::integer[])))                      Rows Removed by Filter: 7652                ->  Index Only Scan using taggings_idx on taggings users_trait_taggings_356a192  (cost=0.42..22767.59 rows=11393 width=4) (actual time=0.048..16.009 rows=4554 loops=1)                      Index Cond: ((tag_id = 2) AND (taggable_type = 'User'::text) AND (context = 'trait'::text))                      Heap Fetches: 4554          ->  Index Scan using index_taggings_on_taggable_id_and_taggable_type_and_context on taggings users_trait_taggings_5df4b2a  (cost=0.42..2.16 rows=1 width=4) (actual time=0.016..0.016 rows=0 loops=1351)                Index Cond: ((taggable_id = users.id) AND ((taggable_type)::text = 'User'::text) AND ((context)::text = 'trait'::text))                Filter: (tag_id = ANY ('{4,6}'::integer[]))                Rows Removed by Filter: 2  Total runtime: 2243.913 ms  

Complete version here.

It seems like there's something wrong with Index Scan using users_pkey on users where the index scan is taking a very long time. Even though there's an index on age, number_of_photos and the id:

add_index "users", ["age"], name: "index_users_on_age", using: :btree  add_index "users", ["number_of_photos"], name: "index_users_on_number_of_photos", using: :btree  

to_skip is an array of user ids to not skip. A user has many skips. Each skip has a partner_id.

So to fetch to_skip I'm doing:

to_skip = @user.skips.pluck(:partner_id)  

I tried to isolate the query to just:

sql = User.limit(20).    where.not(id: to_skip, number_of_photos: 0).    where(age: @user.seeking_age_min..@user.seeking_age_max).to_sql  

And still getting the same problem with the explain analyze. Again, list of user ids is snipped:

Limit  (cost=0.00..435.34 rows=20 width=1698) (actual time=0.219..4.844 rows=20 loops=1)    ->  Seq Scan on users  (cost=0.00..819629.38 rows=37655 width=1698) (actual time=0.217..4.838 rows=20 loops=1)          Filter: ((id IS NOT NULL) AND (number_of_photos <> 0) AND (age >= 18) AND (age <= 99) AND (id <> ALL ('{7066,7065,...,15624,23254}'::integer[])))          Rows Removed by Filter: 6  Total runtime: 5.044 ms  

Complete version here.

Any thoughts on how I can optimize this query in rails + postgres?

EDIT: Here are the relevant models:

User model

class User < ActiveRecord::Base    acts_as_messageable required: :body, # default [:topic, :body]                        dependent: :destroy      has_many :skips, :dependent => :destroy      acts_as_taggable # Alias for acts_as_taggable_on :tags    acts_as_taggable_on :seeking_gender, :trait, :seeking_race    scope :by_updated_date, -> {      order("updated_at DESC")    }  end    # schema    create_table "users", force: :cascade do |t|    t.string   "email", default: "", null: false    t.datetime "created_at", null: false    t.datetime "updated_at", null: false    t.text     "skips", array: true    t.integer  "number_of_photos", default: 0    t.integer  "age"  end    add_index "users", ["age"], name: "index_users_on_age", using: :btree  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree  add_index "users", ["number_of_photos"], name: "index_users_on_number_of_photos", using: :btree  add_index "users", ["updated_at"], name: "index_users_on_updated_at", order: {"updated_at"=>:desc}, using: :btree  

Skips model

class Skip < ActiveRecord::Base    belongs_to :user  end    # schema    create_table "skips", force: :cascade do |t|    t.integer  "user_id"    t.integer  "partner_id"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end    add_index "skips", ["partner_id"], name: "index_skips_on_partner_id", using: :btree  add_index "skips", ["user_id"], name: "index_skips_on_user_id", using: :btree  

Evaluate the title is correct in the view (rendered)

Posted: 30 Jul 2016 01:45 AM PDT

I have an URL: http://myweb:2000/value.json. which display json array like

[{ id:1, t: "new"},{ id:2, t: "wel"}]  

Controller:

FactoryGirl.define do   factory :model_data do   id 1   t "MyString"  end    end  

Rspec code require 'spec_helper'

 describe "retrieve data" do   before(:all) do     DatabaseCleaner.start     @c1 = ModelData.new(id: '1', t: 'new')  end     after(:all) do       DatabaseCleaner.clean   end   it "returns no of objects" do  get 'value.json'  expect(JSON.parse(response.body)).to have(2).items  end  end  

controller code i have update. I am new to rspec please help.

rails redirect to edit page when submitting the form with the params of saved form

Posted: 30 Jul 2016 12:04 AM PDT

I'm new to rails,I've created a customer_details form.when I submit a form by clicking save button It should be saved and redirected to the edit page with all the contents of the form.so that i can download the form using download button.This is what im getting after saved the form

def create      @customer_detail = CustomerDetail.new(customer_detail_params)      @customer_detail.company_profile_id = current_user.company_profile.id      respond_to do |format|        if @customer_detail.save          format.html { redirect_to edit_customer_detail_path(@customer_detail), notice: 'customerDetails was successfully created.' }        else          format.html { render :new }        end      end    end  def edit     @customer_details = CustomerDetail.find(params[:id])    end
problem is,when I click save button it redirects to the edit path.but without any contents of form. what should I do now to get the form in edit_path?.can someone plz help me.thanks in advance!!

No comments:

Post a Comment