Friday, August 12, 2016

Missing Image when using paperclip gem | Fixed issues

Missing Image when using paperclip gem | Fixed issues


Missing Image when using paperclip gem

Posted: 12 Aug 2016 08:34 AM PDT

I am trying to use the paperclip gem to display images but the output i get it missing image

Below is the controller and model files respectively

Controlfile

class HandymenController < ApplicationController before_action :find_handyman, only: [:show, :edit, :update, :destroy]

def index      if params[:profession].blank?          @handymen = Handyman.all.order("created_at DESC")      else          @profession_id = Profession.find_by(name: params[:profession]).id          @handymen = Handyman.where(:profession_id => @profession_id).order("created_at DESC")      end   end    def show  end     def new      @handyman = current_user.handymen.build      @professions = Profession.all.map{ |p| [p.name, p.id] }  end    def create      @handyman = current_user.handymen.build(handyman_params)      @handyman.profession_id = params[:profession_id]        if @handyman.save          redirect_to root_path      else          render 'new'      end  end     def edit      @professions = Profession.all.map{ |p| [p.name, p.id] }  end    def update      @handyman.profession_id = params[:profession_id]      if @handyman.update(handyman_params)          redirect_to handyman_path(@handyman)      else          render 'edit'      end  end    def destroy      @handyman.destroy      redirect_to root_path  end    private    def handyman_params      params.require(:handyman).permit(:name, :location, :phone_number, :profession_id, :handyman_img)  end     def find_handyman      @handyman = Handyman.find(params[:id])  end  

end

Model File

class Handyman < ActiveRecord::Base belongs_to :user belongs_to :profession

has_attached_file :handyman_img, styles: { handyman_index: "250x350>", handyman_show: "325x475>" } validates_attachment_content_type :handyman_img, content_type: /\Aimage/.*\Z/ end

Impossible to run a Rails console on heroku with Attachinary: undefined method `respond_to' for Attachinary::CorsController:Class

Posted: 12 Aug 2016 08:31 AM PDT

I am running a Rails app uploading images with a Cloudinary/Attachinary configuration.Locally, everything is fine, my app run and I can upload pictures to Cloudinary. I can push on Heroku, migrations are OK, config vars too but the app crashes with that error:

<class:CorsController>': undefined method `respond_to' for Attachinary::CorsController:Class (NoMethodError)  

Some help would be really appreciated.

Thanks,

Kevin

deploy rails app to heroku failed

Posted: 12 Aug 2016 08:27 AM PDT

i'm trying to deploy my rails app to heroku for first time and my project already on github i tryed to do Deploy a GitHub branch from https://dashboard.heroku.com but it does't work . does anyone know what is missing . thanks

git push heroku master  Counting objects: 98, done.  Delta compression using up to 4 threads.  Compressing objects: 100% (88/88), done.  Writing objects: 100% (98/98), 17.75 MiB | 709.00 KiB/s, done.  Total 98 (delta 13), reused 0 (delta 0)  remote: Compressing source files... done.  remote: Building source:  remote:   remote: -----> Ruby app detected  remote: -----> Compiling Ruby/Rails  remote: -----> Using Ruby version: ruby-2.2.4  remote: -----> Installing dependencies using bundler 1.11.2  remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment  remote:        Warning: the running version of Bundler is older than the version that created the lockfile. We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.  remote:        Fetching gem metadata from https://rubygems.org/...........  remote:        Fetching version metadata from https://rubygems.org/...  remote:        Fetching dependency metadata from https://rubygems.org/..  remote:        Installing i18n 0.7.0  remote:        Installing rake 11.2.2  remote:        Installing json 1.8.3 with native extensions  remote:        Installing minitest 5.9.0  remote:        Installing thread_safe 0.3.5  remote:        Installing builder 3.2.2  remote:        Installing erubis 2.7.0  remote:        Installing mini_portile2 2.1.0  remote:        Installing pkg-config 1.1.7  remote:        Installing rack 1.6.4  remote:        Installing mime-types-data 3.2016.0521  remote:        Installing arel 6.0.3  remote:        Installing execjs 2.7.0  remote:        Installing sass 3.4.22  remote:        Installing coffee-script-source 1.10.0  remote:        Installing thor 0.19.1  remote:        Installing diff-lcs 1.2.5  remote:        Installing multi_json 1.12.1  remote:        Installing concurrent-ruby 1.0.2  remote:        Using bundler 1.11.2  remote:        Installing rails_stdout_logging 0.0.5  remote:        Installing rails_serve_static_assets 0.0.5  remote:        Installing rspec-support 3.5.0  remote:        Installing tilt 2.0.5  remote:        Installing sqlite3 1.3.11 with native extensions  remote:        Installing turbolinks-source 5.0.0  remote:        Gem::Ext::BuildError: ERROR: Failed to build gem native extension.  remote:        /tmp/build_710878816823bc5564b80a5f8fc7d881/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160812-220-19veaby.rb extconf.rb  remote:        checking for sqlite3.h... no  remote:        sqlite3.h is missing. Try 'port install sqlite3 +universal',  remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'  remote:        and check your shared library search path (the  remote:        location where your sqlite3 shared library is located).  remote:        *** extconf.rb failed ***  remote:        Could not create Makefile due to some reason, probably lack of necessary  remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may  remote:        need configuration options.  remote:        Provided configuration options:  remote:        --with-opt-dir  remote:        --without-opt-dir  remote:        --with-opt-include  remote:        --without-opt-include=${opt-dir}/include  remote:        --with-opt-lib  remote:        --without-opt-lib=${opt-dir}/lib  remote:        --with-make-prog  remote:        --without-make-prog  remote:        --srcdir=.  remote:        --curdir  remote:        --ruby=/tmp/build_710878816823bc5564b80a5f8fc7d881/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME)  remote:        --with-sqlite3-dir  remote:        --without-sqlite3-dir  remote:        --with-sqlite3-include  remote:        --without-sqlite3-include=${sqlite3-dir}/include  remote:        --with-sqlite3-lib  remote:        --without-sqlite3-lib=${sqlite3-dir}/lib  remote:        extconf failed, exit code 1  remote:        Gem files will remain installed in /tmp/build_710878816823bc5564b80a5f8fc7d881/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection.  remote:        Results logged to /tmp/build_710878816823bc5564b80a5f8fc7d881/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out  remote:        Installing tzinfo 1.2.2  remote:        Installing rack-test 0.6.3  remote:        Installing nokogiri 1.6.8 with native extensions  remote:        Installing rdoc 4.2.2  remote:        Installing mime-types 3.1  remote:        Installing autoprefixer-rails 6.3.7  remote:        Installing uglifier 3.0.1  remote:        Installing coffee-script 2.4.1  remote:        Installing bootstrap-sass 3.2.0.2  remote:        Installing sprockets 3.7.0  remote:        Installing rspec-core 3.5.2  remote:        Installing rspec-expectations 3.5.0  remote:        Installing rspec-mocks 3.5.0  remote:        Installing rails_12factor 0.0.3  remote:        Installing turbolinks 5.0.1  remote:        An error occurred while installing sqlite3 (1.3.11), and Bundler cannot  remote:        continue.  remote:        Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.  remote:        Bundler Output: Warning: the running version of Bundler is older than the version that created the lockfile. We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.  remote:        Fetching gem metadata from https://rubygems.org/...........  remote:        Fetching version metadata from https://rubygems.org/...  remote:        Fetching dependency metadata from https://rubygems.org/..  remote:        Installing i18n 0.7.0  remote:        Installing rake 11.2.2  remote:        Installing json 1.8.3 with native extensions  remote:        Installing minitest 5.9.0  remote:        Installing thread_safe 0.3.5  remote:        Installing builder 3.2.2  remote:        Installing erubis 2.7.0  remote:        Installing mini_portile2 2.1.0  remote:        Installing pkg-config 1.1.7  remote:        Installing rack 1.6.4  remote:        Installing mime-types-data 3.2016.0521  remote:        Installing arel 6.0.3  remote:        Installing execjs 2.7.0  remote:        Installing sass 3.4.22  remote:        Installing coffee-script-source 1.10.0  remote:        Installing thor 0.19.1  remote:        Installing diff-lcs 1.2.5  remote:        Installing multi_json 1.12.1  remote:        Installing concurrent-ruby 1.0.2  remote:        Using bundler 1.11.2  remote:        Installing rails_stdout_logging 0.0.5  remote:        Installing rails_serve_static_assets 0.0.5  remote:        Installing rspec-support 3.5.0  remote:        Installing tilt 2.0.5  remote:        Installing sqlite3 1.3.11 with native extensions  remote:        Installing turbolinks-source 5.0.0  remote:          remote:        Gem::Ext::BuildError: ERROR: Failed to build gem native extension.  remote:          remote:        /tmp/build_710878816823bc5564b80a5f8fc7d881/vendor/ruby-2.2.4/bin/ruby -r ./siteconf20160812-220-19veaby.rb extconf.rb  remote:        checking for sqlite3.h... no  remote:        sqlite3.h is missing. Try 'port install sqlite3 +universal',  remote:        'yum install sqlite-devel' or 'apt-get install libsqlite3-dev'  remote:        and check your shared library search path (the  remote:        location where your sqlite3 shared library is located).  remote:        *** extconf.rb failed ***  remote:        Could not create Makefile due to some reason, probably lack of necessary  remote:        libraries and/or headers.  Check the mkmf.log file for more details.  You may  remote:        need configuration options.  remote:          remote:        Provided configuration options:  remote:        --with-opt-dir  remote:        --without-opt-dir  remote:        --with-opt-include  remote:        --without-opt-include=${opt-dir}/include  remote:        --with-opt-lib  remote:        --without-opt-lib=${opt-dir}/lib  remote:        --with-make-prog  remote:        --without-make-prog  remote:        --srcdir=.  remote:        --curdir  remote:        --ruby=/tmp/build_710878816823bc5564b80a5f8fc7d881/vendor/ruby-2.2.4/bin/$(RUBY_BASE_NAME)  remote:        --with-sqlite3-dir  remote:        --without-sqlite3-dir  remote:        --with-sqlite3-include  remote:        --without-sqlite3-include=${sqlite3-dir}/include  remote:        --with-sqlite3-lib  remote:        --without-sqlite3-lib=${sqlite3-dir}/lib  remote:          remote:        extconf failed, exit code 1  remote:          remote:        Gem files will remain installed in /tmp/build_710878816823bc5564b80a5f8fc7d881/vendor/bundle/ruby/2.2.0/gems/sqlite3-1.3.11 for inspection.  remote:        Results logged to /tmp/build_710878816823bc5564b80a5f8fc7d881/vendor/bundle/ruby/2.2.0/extensions/x86_64-linux/2.2.0-static/sqlite3-1.3.11/gem_make.out  remote:        Installing tzinfo 1.2.2  remote:        Installing rack-test 0.6.3  remote:        Installing nokogiri 1.6.8 with native extensions  remote:        Installing rdoc 4.2.2  remote:        Installing mime-types 3.1  remote:        Installing autoprefixer-rails 6.3.7  remote:        Installing uglifier 3.0.1  remote:        Installing coffee-script 2.4.1  remote:        Installing bootstrap-sass 3.2.0.2  remote:        Installing sprockets 3.7.0  remote:        Installing rspec-core 3.5.2  remote:        Installing rspec-expectations 3.5.0  remote:        Installing rspec-mocks 3.5.0  remote:        Installing rails_12factor 0.0.3  remote:        Installing turbolinks 5.0.1  remote:        An error occurred while installing sqlite3 (1.3.11), and Bundler cannot  remote:        continue.  remote:        Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.  remote:  !  remote:  !     Failed to install gems via Bundler.  remote:  !       remote:  !     Detected sqlite3 gem which is not supported on Heroku.  remote:  !     https://devcenter.heroku.com/articles/sqlite3  remote:  !  remote:  !     Push rejected, failed to compile Ruby app.  remote:   remote:  !     Push failed  remote: Verifying deploy...  remote:   remote: !	Push rejected to nutsandtea.  remote:   To https://git.heroku.com/nutsandtea.git   ! [remote rejected] master -> master (pre-receive hook declined)  error: failed to push some refs to 'https://git.heroku.com/nutsandtea.git'

Scoping with multiple operations over multiple fields

Posted: 12 Aug 2016 08:18 AM PDT

My goal is do a lot of filtering over some ActiveRecords.

My ideal end game is something like this: SalesForce screen shot. (Not pictured: field names can be dragged an dropped from offscreen. I typed "FOOBAR", specified "equals" and clicked okay for the Account Name field. I then dragged the Type field).

Desired functionality: Filter a model based on user input. The user might specify a number of fields over which to filter along with an operation for each of those fields. (Maybe a little more complicated -- I would ideally like to query over non-field methods. EX: Say a User has_many: pets. It would be nice to be able to filter users with more than 3 pets.)

Most of the fields are text, so I would imagine [contains], [does not contain], [starts with], [ends with], and [equals] will be the dominant scopes needed.

Attempts:

  • I have looked at "http://filterrific.clearcove.ca/" and "has_scope", but I'm not entirely sure how to implement cleanly. (Ties into following bullet:)
  • Dynamically generate scopes in rails models seems handy, because I'm working with something like WHITELISTED_OPERATIONS = ["=", "!=", ">", "<", ">=", "<="]. However, this answer is a few years old at this point.
  • If worse comes to worse, I could implement each of the operations for each of the fields, but that seems inelegant.

I appreciate your time.

Backbone: model is not being updated

Posted: 12 Aug 2016 08:16 AM PDT

I have a model which when added is working fine. But it is not being updated. However it is being updated on server.

I'm using model.set() function to set the new attributes and .save() for ajax call to server.

Here's the code

**some code above**    if @type is "Add"    @questionCollection.create(questionToSend, {success: @saveSuccess}, {error: @saveError})  else    @questionToUpdate = @questionCollection.get(@question.id)    @questionToUpdate.set(questionToSend).save(null, {      success: @saveSuccess      error: @saveError    })    saveSuccess: (device,  response) =>    Pulse.notify "Successfully #{if @type is "Update" then "updated" else "added"} question details.", "success"    console.log @questionToUpdate    console.log @questionCollection    @close()    saveError: =>    Pulse.notify "Something went wrong, We are working on fixing the problem.", "error"  

Both console log show old value of the model.

I even tried @questionCollection.set(@questionToUpdate) and {async:false} in the .save() function. I have been struggling with this from two days. Please help out.

There is some other view which uses these collection which are not being updated.

Rails Form Not hitting Action

Posted: 12 Aug 2016 07:39 AM PDT

So, I have created an action in my transactions(tx) controller in order to update an order with an API call. The form is in the purchase confirmation page and its an ajax request.

def deduct_shipping_cost    @transaction = Bid.find(params[:id]).tx    if @transaction.update(transaction_params)      @transaction.bid.shipping_cost = 0      @transaction.bid.calculate_total_amount      p @transaction.bid      p ArmorPaymentsApi.update_order(@transaction.bid, "message" => "Buyer will be using their freight account #. Shipping costs that were quoted have been deducted from the order.")    end  end  

that is the action in my controller

post 'update_order' => 'transactions#deduct_shipping_cost', as: "deduct_shipping_cost"  

that is the route

and here what the form looks like

.form-container    = form_for(deduct_shipping_cost_path, html: { class: "inline-form" }, remote: true) do |f|      .field.form-group.freight_num        = f.text_field :shipping_account, class: "form-control", placeholder: "Account #"      .actions.freight_num.send_ship_num{style: "margin-bottom: 20px;"}        = f.submit 'Submit', class: "btn custom-btn"`  

The server shows the data I am submitting but it doesn't update the @transaction nor does it do anything in the controller action

Query consecutive days records effectively

Posted: 12 Aug 2016 08:09 AM PDT

Query consecutive days records effectively.

Let's say I have tables hotels, rooms, room_skus

Hotel HAS_MANY Room

Room HAS_MANY RoomSku (RoomSku has a date field)

inline

I can take the location and date_range as the params from the user.

eg. L.A. 2016-08-12~2016-08-18

The above params mean I need to fileter all the hotels in L.A. first. And then find the rooms which have available room_skus from 2016-08-12~2016-08-18

How could I write the query more effeciently.

The query in PostgreSQL looks like this

      Room Load (0.7ms)  SELECT "rooms".* FROM "rooms" WHERE "rooms"."id" IN (492, 76, 1187)        Hotel Load (0.6ms)  SELECT "hotels".* FROM "hotels" WHERE "hotels"."id" IN (13, 42,  357, 368, 378)        RoomSku Load (3.6ms)  SELECT "room_skus".* FROM "room_skus" WHERE "room_skus"."room_id" IN (73, 74, 75, 2267)  ORDER BY date         (0.2ms)  SELECT SUM("room_sku_stocks"."amount") FROM "room_sku_stocks" WHERE "room_sku_stocks"."room_sku_id" = $1  [["room_sku_id", 1047]]        HotelImage Load (0.2ms)  SELECT  "hotel_images".* FROM "hotel_images" WHERE "hotel_images"."hotel_id" = $1  ORDER BY "hotel_images"."id" ASC LIMIT 1  [["hotel_id", 13]]         (0.2ms)  SELECT SUM("room_sku_stocks"."amount") FROM "room_sku_stocks" WHERE "room_sku_stocks"."room_sku_id" = $1  [["room_sku_id", 1034]]        CACHE (0.0ms)  SELECT  "hotel_images".* FROM "hotel_images" WHERE "hotel_images"."hotel_id" = $1  ORDER BY "hotel_images"."id" ASC LIMIT 1  [["hotel_id", 13]]         (0.2ms)  SELECT SUM("room_sku_stocks"."amount") FROM "room_sku_stocks" WHERE "room_sku_stocks"."room_sku_id" = $1  [["room_sku_id", 1021]]        .....        CACHE (0.0ms)  SELECT  "hotel_images".* FROM "hotel_images" WHERE "hotel_images"."hotel_id" = $1  ORDER BY "hotel_images"."id" ASC LIMIT 1  [["hotel_id", 378]]        Rendered api/v1/room_skus/search.json.jbuilder (468.4ms)  

Here's my current query, its complexity looks so terrible.

      // suppose I get the hotel ids first, and try to filter available rooms from this function        def get_available_rooms_in_a_row(start_date, end_date, hotel_ids, num_of_days_in_a_row)          all_room_ids = RoomSku.get_room_ids(start_date, end_date, hotel_ids)          available_rooms_ids = get_filtered_available_rooms_ids(all_room_ids, num_of_days_in_a_row)          Room.includes(:hotel, :skus).where(id: available_rooms_ids)        end  

# fetch all room_sku_ids and check if the # of available room_sku_ids is above the num_of_days_in_a_row, # if so, then this room is qualified. (the filter is on Ruby level not SQL level)

          def get_filtered_available_rooms_ids(room_ids, num_of_days_in_a_row)              room_frequence = {}              room_ids.each do |i|                if room_frequence.has_key? i                  room_frequence[i]+=1                else                  room_frequence[i] = 1                end              end              room_frequence.reject { |k, v| v < num_of_days_in_a_row }.keys            end  

And in the response JSON is also a headache question,

I will get Rooms from the above functions,

But the returned JSON is a aggregation of valia room_sku_ids and its Hotel and Room infomation.

Let's say. The return Rooms are #1 and #2

However, the Room #1 has room_sku_ids from 2016-01-01 ~ 2018-12-31

But what I need is the info of room_sku_ids from 2016-08-12~2016-08-18

Therefore you can see I wrote a isOutOfDataRange to filter those room_sku_ids which are out of date range.

        def isOutOfDataRange(room_sku_date)            (room_sku_date< @checkin_date or room_sku_date > @checkout_date )          end            json.array!(@rooms) do |item|            json.hotel item.hotel            json.room_skus do              json.array! item.skus do |sku|                next if isOutOfDataRange(sku.date)                json.merge! sku.attributes.merge({stock:sku.stock})              end            end          end  

Overall, I think these query is terrible and not-effective.

Any idea or direction to prove my code?

Sample output: Object of Array, each object is a aggregation of RoomSkuid and its Room, Hotel information

inline

SAMPLE JSON

  [         {            "id":73,          "hotel_id":13,          "name":"單人房",          "guests":1,          "created_at":"2016-08-10T17:03:40.302Z",          "updated_at":"2016-08-10T17:03:40.302Z",          "english_name":"Single Room",          "hotel":{               "id":13,             "name":"東京郎伍德飯店",             "introduction":null,             "city_id":1,             "created_at":"2016-08-10T17:03:40.300Z",             "updated_at":"2016-08-10T17:03:40.311Z",             "checkin_time":null,             "checkout_time":null,             "region":"上野",             "english_name":"Hotel Lungwood Tokyo",          },          "room_skus":[               {                  "id":1047,                "room_id":73,                "price":4000,                "date":"2016-08-17",                "created_at":"2016-08-10T17:04:05.161Z",                "updated_at":"2016-08-10T17:04:05.170Z",                "saleable":true,                "annotation":null,                "state":"active",                "cost":3000.0,                "stock":6             }          ],          "img_src_url":"/img/hotel.jpg"       },       .....       {            "id":2267,          "hotel_id":378,          "name":"三人房",          "guests":3,          "created_at":"2016-08-10T17:03:45.364Z",          "updated_at":"2016-08-10T17:03:45.364Z",          "english_name":"Triple Room",          "hotel":{               "id":378,             "name":"名古屋駅前名鐵飯店",             "introduction":null,             "city_id":3,             "created_at":"2016-08-10T17:03:45.357Z",             "updated_at":"2016-08-10T17:03:45.367Z",             "checkin_time":null,             "checkout_time":null,             "region":"名古屋",             "english_name":"Meitetsu Inn Nagoya Ekimae",          },          "room_skus":[               {                  "id":30690,                "room_id":2267,                "price":3000,                "date":"2016-08-17",                "saleable":true,                "annotation":null,                "state":"active",                "cost":2500.0,                "stock":26             }          ],          "img_src_url":"/img/hotel.jpg"       }    ]  

How to select rows by comparing two sums on child tables, without subqueries?

Posted: 12 Aug 2016 07:35 AM PDT

I have a schema that looks like the following:

Invoices:        | id | ... |  InvoicePayments: | id | invoice_id | amount_cents | ... |  LineItems:       | id | invoice_id | unit_price_cents | quantity | ... |  

and I am looking to find unpaid invoices, that is, Invoices who have a sum of amount_cents from InvoicePayments that is less than the sum of (quantity * unit_price) from LineItems. I was able to accomplish this with two sub queries, like:

SELECT prices.id FROM (    SELECT invoices.id, sum(invoice_payments.amount_cents) as paid    FROM invoices    LEFT JOIN invoice_payments ON invoice_payments.invoice_id = invoices.id    GROUP BY invoices.id  ) payments JOIN (    SELECT invoices.id, sum(line_items.quantity * line_items.unit_price_cents) as price    FROM invoices    LEFT JOIN line_items ON line_items.invoice_id = invoices.id    GROUP BY invoices.id  ) prices  ON payments.id = prices.id  WHERE paid < price OR paid IS NULL;  

However, I am using ActiveRecord and would like something simpler that could be translated into Arel statements; additionally, I would like to use this as a reusable scope, so I could apply additional constraints, such as finding Invoices that were unpaid on a certain date, by filtering out InvoicePayments that are newer than that date.

Is there a way to accomplish this without subqueries so that I can use this more easily with Rails and apply flexible filters?

Ruby - how to extract £ symbol in a string to float conversion

Posted: 12 Aug 2016 07:19 AM PDT

I'm using Ruby On Rails to build an events app. I'm trying desperately to find a way to handle multiple bookings for a user - so they can choose to book multiple spaces (at the moment they can only book one at a time) and the app will convert that number into the correct price ( 10 tickets for £10 each will cost £100 etc). With the help of SO & Google, I've looked at a number of methods to use in my bookings.rb model, this is the latest -

def total_amount      quantity.to_i * strip_currency(event.price)  end    private        def strip_currency(amount = '')          amount.to_s.gsub(/[^\d\.]/, '').to_f      end  

I've also tried this -

    def total_amount         self.quantity.to_i * self.event.price.to_f      end  

Both methods return 0(zero) when I click through to the payments page. It basically boils down to the £ symbol (or am I missing something else?). It's been suggested that this equation may work -

string[0..-1].to_f  

However, I'm pretty new to this and not sure how or where I would integrate this into my MVC code in order for it to work. I'm not using the monetize gem, I'm using money-rails but there must be a simple way / line(s) of code that will allow this method to work.

Am I barking up the wrong tree with Ruby - should I be using javascript for this?

pry web page gui similar to better_errors web page gui

Posted: 12 Aug 2016 07:10 AM PDT

The pry-rails gem is awesome as it lets you set break points in your application and inspect various things about the app's current state. However: it is all done in a terminal window.

I love the better_errors gem combined with the binding_of_caller gem because not only does it return a bunch of useful information in a web-page gui: but it also has an interactive shell which allows you to inspect the current state, similar to pry.

The issue is that the better_errors gem is not made for setting break points. For example: you cannot set a break point and then continue with the better_errors gem.

What I am looking for is a hybrid. I want to set up break points like how I do with pry in my rails app. When the app hits the break point: I want a web page gui to appear similar to how it works with the better_errors gem. I then want to be able to continue which better_errors cannot do.

Question: Is there a gem out there that will make my pry breakpoints open up a web page gui similar to better_errors and binding of caller? If not: is there some other gem out there that allows me to set breakpoints, inspect in the webpage gui, and then continue?

is there a difference between strong parameters and having no attr_accessible using direct assigs only?

Posted: 12 Aug 2016 06:53 AM PDT

without the point, that it is less code to write ...

I don't want to discuss strong parameters, I just want to know if I missed something related to security

so (after found a @user)

up=params[:user]  fields=[:name]  fields+=[:nick, :banned] if logged_in_user_is_admin  fields.each do |f|       @user[f] = up[f] if up[f].present?   end   @user.save  

and

fields=[:name]  fields+=[:nick, :banned] if logged_in_user_is_admin  @user.require(:user).update_attributes!.permit(*fields)  

should do the same - without talking about error handling

Am I right? Or is there more behind the scene?

Rails : Simple search form, with keywords jambled

Posted: 12 Aug 2016 07:06 AM PDT

I've made a simple search for my rails app. But I want to make it works, even with keywords jambled. If I have a tweet with "hello world" written, I can sort it by typing "hello world" but it doesn't work if I type "world hello". How can I fix it ? Here is my code :

tweet_controller.rb

def index   @tweets = Tweet.all    if params[:search]      @tweets = Tweet.search(params[:search])    else      @tweets = Tweet.all    end  end  

tweet.rb

def self.search(search)    where("status LIKE ?", "%#{search}%")  end  

and the view

<%= form_tag(tweets_path, :method => "get", id: "search-form") do %>    <%= text_field_tag :search, params[:search], placeholder: "Search Tweets" %>    <%= submit_tag "Search" %>  <% end %>  

Thanks !

Rails 4: Uploading data uri to Cloudinary

Posted: 12 Aug 2016 07:32 AM PDT

I'm using Heroku and I have the Cloudinary running with my project. The upload works fine, but when I try to upload some Data Uri to Cloudnary its not work. I saw the documentation and I know I have to use the function. I'm using carrierwave-data-uri to generate images from data-uri, It works locally, but when I change the code to integra with Cloudinary I get empty images on cloud

I know I have to use the function Cloudinary::Uploader.upload(photo) but it is not clear to me how can I integrate it to my function:

  def upload_image      photo = params[:picture][:photo]        @picture = Picture.new(picture_params)      @picture.photo_data_mimetype = 'image/jpeg'      @picture.user_id = current_user.id       @picture.photo_data_uri = photo      @picture.save    end  

This method receives data from ajax. If I just do Cloudinary::Uploader.upload(photo), the image is not associated with the record in my database

I tried the code below, but I get the error undefined method secure_url:

  def upload_image      photo = params[:picture][:photo]        @picture = Picture.new(picture_params)      @picture.photo_data_mimetype = 'image/jpeg'      @picture.user_id = current_user.id       cl_image = Cloudinary::Uploader.upload(photo)        @picture.photo = cl_image.secure_url      @picture.save    end  

Thanks by help!

Rails - Mail_form how to automatically set "from" field to current_user email

Posted: 12 Aug 2016 06:55 AM PDT

I followed this guide https://rubyonrailshelp.wordpress.com/2014/01/08/rails-4-simple-form-and-mail-form-to-make-contact-form/

In the contact form, the user fills out a field for their name and email along with the message.

class ContactForm < MailForm::Base      attribute :name,      :validate => true    attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i    attribute :message    attribute :nickname,  :captcha  => true      # Declare the e-mail headers. It accepts anything the mail method    # in ActionMailer accepts.    def headers      {        :subject => "My Contact Form",        :to => "FILLTHISIN@example.com",        :from => %("#{name}" <#{email}>)      }    end  end  

I want to automatically send from the user.email attribute and not have the user fill out a field. Is this possible?

Customizing Bootstrap SASS variables in Rails

Posted: 12 Aug 2016 08:27 AM PDT

I need to reduce the font-size of Bootstrap's Jumbotron header in Rails. I see here

that I need to add something like

@jumbotron-heading-font-size: ceil((@font-size-base * 2.5));  

in my file

app/assets/stylesheets/bootstrap_customization.css.scss  

So I changed "@" to "$", please see below how the file looks now:

$jumbotron-heading-font-size: ceil(($font-size-base * 2.5));  $jumbotron-padding: 20px;  @import "bootstrap";  

But this doesn't work.

Mysql : Access denied for user 'root'@'localhost'

Posted: 12 Aug 2016 07:38 AM PDT

I'm a noob in database, and I don't know what to do to solve this problem.

I'm trying to launch that project Sharetribe which is an open source project.

When I try to run this command

bundle exec rake db:create  

I get :

Access denied for user 'root'@'localhost' (using password: NO)Please provide the root password for your MySQL installation

Here is my file database.yml

development:    adapter: mysql2    database: sharetribe_development    encoding: utf8    username: root    password: "my_root_password"    host: localhost    # Warning: The database defined as "test" will be erased and  # re-generated from your development database when you run "rake".  # Do not set this db to the same as development or production.  test: &test    adapter: mysql2    database: sharetribe_test    encoding: utf8    username: root    password: "my_root_password"    host: localhost    staging:    adapter: mysql2    database: sharetribe_staging    encoding: utf8    username: root    password: "my_root_password"    host: localhost    production:    adapter: mysql2    database: sharetribe_production    encoding: utf8    username: root    password: "my_root_password"    host: localhost    cucumber:    <<: *test  

What I already tried :

  • Change the root user password
  • Start then stop mysql server

How to check if array from MySQL DB includes the given value

Posted: 12 Aug 2016 06:54 AM PDT

I have already tried THIS answer. But, it gives me empty ActiveRecord::Relation. So here is a way I have tried:

Model

class ChatUser < ActiveRecord::Base    serialize :show_for, Array      scope :reviewee, -> { where("user_type = ?", "reviewee") }      def self.for_manager(current_user)      select{|chat_user| chat_user.show_for.include?(current_user.id)}      # where("FIND_IN_SET(1, show_for)") <-- doesn't work    end  end  

Sample Data

<ChatUser id: 773, show_for: [1], user_type: "reviewee">  

Code Tried

ChatUser.reviewee.for_manager(current_user) //current_user is User.first with id 1  

But, it always gives me blank instead of object with id 773.

Ruby on Rails Installation error on Ubuntu Linux 14.04

Posted: 12 Aug 2016 06:32 AM PDT

I'm getting problem while installing rails in Linux. Permission error is coming when i'm trying to run gem install rails.Still i'm getting this error.

how to get method from another file undefined method

Posted: 12 Aug 2016 08:29 AM PDT

In my query mysql file i try to include my FileDataRead module to read and get the params for etablish the connection.

I don't see what I've missed :(

The error:

logger': undefined method `read_config_file' for Logging:Module (NoMethodError)

My loging module file:

module Logging    include FileDataRead      def logger      Logging.logger    end      def self.logger      @conf = read_config_file('logging')      @logger ||= Logger.new(@conf['name'])      @logger.formatter = proc { |severity, datetime, progname, msg|                                "[#{datetime.strftime('%F %T')}] #{msg}\n"                               }      @logger    end  end  

The reading file:

require 'yaml'    module FileDataRead    #include logger      def read_config_file(var)      config = YAML::load_file(File.join('config.yml'))      if var == 'database'      # logger.info("database".colorize("cyan", :style =>"strikethrough"))        puts "database"        @conf = config['database']      elsif var == 'logging'        puts "logging"        @conf = config['logging']      elsif var == "mail"        @conf = config['mail']      end    end  end  

Unable to run gem rails. Cannot find 'rails' rubymine error [duplicate]

Posted: 12 Aug 2016 07:51 AM PDT

This question already has an answer here:

I get this problem whenever I want to start a new rails project in RubyMine. This issue has been sorted before here but the solution makes absolute no sense to me thus still stranded. Would love it in detailed simple words.

Ruby/Rails console autocomplete and search forward/backward from history

Posted: 12 Aug 2016 05:09 AM PDT

I live in both Ruby and Python worlds and one of the features I really appreciate from iPython is autocomplete by up/down from any column of a input query to the console. That is, it can find all historical matches which match anything to the left of where I place the cursor.

For instance, with this as input, I'd like to hit the up key and get an auto-fill with the last similar command I ran:

irb(main):001:0> Order.where(<cursor> # up/down here to view similar history  

Even better still would be if as I continue to hit the up key, I would then be able to continue cycling through similar commands, still based off the original cursor column at which I began. That is, I don't want to get one and then have the cursor at the end and find similar commands to.

If it helps, here's how I achieve that in bash for my profile, I'd just like to have this in a ruby/rails console too:

$ cat ~/.inputrc  # this makes the "delete" key work rather than  # just entering a ~  "\e[3~": delete-char    # these allow you to use ctrl+left/right arrow keys  # to jump the cursor over words  "\e[5C": forward-word  "\e[5D": backward-word    # these allow you to start typing a command and  # use the up/down arrow to auto complete from  # commands in your history  "\e[B": history-search-forward  "\e[A": history-search-backward    # this lets you hit tab to auto-complete a file or  # directory name ignoring case  set completion-ignore-case On    "\e[1~": beginning-of-line  "\e[4~": end-of-line  "\e[5~": beginning-of-history  "\e[6~": end-of-history  "\e[2~": quoted-insert   

I currently have this in my ~/.irbrc, but that doesn't quite accomplish autocompletion of sub-commands for column position greater than zero.

require 'irb/ext/save-history'  IRB.conf[:SAVE_HISTORY] = 200  IRB.conf[:HISTORY_FILE] = "/home/me/.irb-history"  

Is there already a way to do this already in Rails/Ruby or is there a way to achieve this in a rails/ruby console? I've already read Can I get the Ruby on Rails console to remember my command history, umm, better? and How to view the entire Rails console history?, but they don't achieve the level of precision I'm looking for here.

Thanks!

Rails Bootstrap Dropdown Menu not Going Back Up

Posted: 12 Aug 2016 05:07 AM PDT

So I have a rails app that's using Bootstrap and the js dropdown menu will dropdown when clicked, but it won't go back up.

I got it working 100% when I had this same setup on a static site, but on the rails version it seems to be partially broken.

The website is https://www.cabinetsfromscratch.com

I have 2 questions.

  1. How do I fix it?
  2. How do you go about troubleshooting javascript errors, which is what I assume this problem is?

Thanks.

How to configure rails port to work with local OSM tile server?

Posted: 12 Aug 2016 04:58 AM PDT

I successfully installed OSM tile server, and it is working well. Additionally i installed nominatim geocoder and also rails port to abillity edit entire map, that installed on the server. (Maybe there is more simpler way to get API to edit remotely map throught idEditor, but i don't know how to do it) rails port app accessble via 0.0.0.0:3000

My purpose is give users abillity to edit map, that locally installed on the server with iD editor throught browser.

How can I configure rails port app to ideditor worked with a local map, and in the application interface to display tiles downloaded through a local tile server? Sorry for my English. Thank's in advance.

What causes test error 'Running without the SUID sandbox!'?

Posted: 12 Aug 2016 04:03 AM PDT

I'm running rails tests on Circle-CI. The test progress output contains a lot of messages as below. What do these mean, and are they caused by the app or the CI platform? Could an old version of PhantomJS raise this error?

[14462:14462:0812/100648:ERROR:browser_main_loop.cc(173)] Running without the SUID sandbox! See https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment for more information on developing with the sandbox on.  Xlib:  extension "RANDR" missing on display ":99".  [14462:14462:0812/100648:ERROR:browser_main_loop.cc(219)] GLib-GObject: Attempt to add property GtkSettings::gtk-label-select-on-focus after class was initialised  [14462:14462:0812/100648:ERROR:browser_main_loop.cc(219)] GLib-GObject: Attempt to add property GtkSettings::gtk-entry-select-on-focus after class was initialised  [14462:14462:0812/100648:ERROR:browser_main_loop.cc(219)] GLib-GObject: Attempt to add property GtkSettings::gtk-entry-password-hint-timeout after class was initialised  Xlib:  extension "RANDR" missing on display ":99".  [14489:14489:0812/100649:ERROR:sandbox_linux.cc(340)] InitializeSandbox() called with multiple threads in process gpu-process  [14462:14462:0812/100649:ERROR:browser_main_loop.cc(219)] GLib-GObject: Attempt to add property GtkSettings::gtk-button-images after class was initialised  [14518:14518:0812/100649:ERROR:renderer_main.cc(200)] Running without renderer sandbox  [14521:14521:0812/100649:ERROR:renderer_main.cc(200)] Running without renderer sandbox  [14524:14524:0812/100649:ERROR:renderer_main.cc(200)] Running without renderer sandbox  [14533:14533:0812/100649:ERROR:renderer_main.cc(200)] Running without renderer sandbox  [14538:14538:0812/100649:ERROR:renderer_main.cc(200)] Running without renderer sandbox  [14545:14545:0812/100649:ERROR:renderer_main.cc(200)] Running without renderer sandbox  [14462:14462:0812/100649:ERROR:extension_downloader.cc(695)] Invalid URL: '' for extension coobgpohoikkiipiblmjeljniedjpjpf  F[14702:14702:0812/100650:ERROR:renderer_main.cc(200)] Running without renderer sandbox  [14973:14973:0812/100651:ERROR:browser_main_loop.cc(173)] Running without the SUID sandbox! See https://code.google.com/p/chromium/wiki/LinuxSUIDSandboxDevelopment for more information on developing with the sandbox on.  Xlib:  extension "RANDR" missing on display ":99".  [14973:14973:0812/100651:ERROR:browser_main_loop.cc(219)] GLib-GObject: Attempt to add property GtkSettings::gtk-label-select-on-focus after class was initialised  [14973:14973:0812/100651:ERROR:browser_main_loop.cc(219)] GLib-GObject: Attempt to add property GtkSettings::gtk-entry-select-on-focus after class was initialised  [14973:14973:0812/100651:ERROR:browser_main_loop.cc(219)] GLib-GObject: Attempt to add property GtkSettings::gtk-entry-password-hint-timeout after class was initialised  Xlib:  extension "RANDR" missing on display ":99".  [0812/100651:ERROR:nacl_helper_linux.cc(303)] NaCl helper process running without a sandbox!  Most likely you need to configure your SUID sandbox correctly  

Capybara screenshot_and_open_image save whole page

Posted: 12 Aug 2016 04:03 AM PDT

I have issue with screenshot_and_open_image from gem capybara-screenshot

i have large page witch need to be scrolled till the end

i have tried to set resolution for screenshot,doesn't help

How to save whole page not only visible part?

Rails installation fails in ubuntu

Posted: 12 Aug 2016 06:09 AM PDT

I am trying to install Rails on Ubuntu, but it is showing the following error:

ERROR: While executing gem ... (Gem::FilePermissionError) You don't have write permissions into the /var/lib/gems/1.9.1 directory.

Please help me to install the Rails gem.

undefined local variable or method error Rails 4.2.6

Posted: 12 Aug 2016 03:43 AM PDT

I have been referring RailsCasts #396 for importing data from csv, xls, xlas files. According to the railscast (Rails 3.2.9) the import method is

def self.import(file)    spreadsheet = open_spreadsheet(file)    header = spreadsheet.row(1)    (2..spreadsheet.last_row).each do |i|      row = Hash[[header, spreadsheet.row(i)].transpose]      product = find_by_id(row["id"]) || new      product.attributes = row.to_hash.slice(*accessible_attributes)      product.save!    end  end    def self.open_spreadsheet(file)    case File.extname(file.original_filename)    when ".csv" then Csv.new(file.path, nil, :ignore)    when ".xls" then Excel.new(file.path, nil, :ignore)    when ".xlsx" then Excelx.new(file.path, nil, :ignore)    else raise "Unknown file type: #{file.original_filename}"    end  end  

but since Rails 4x implements strong params I was getting undefined local variable or method 'accessible_attributes' error
So I looked up and found this stackoverflow question Rails 4 how to call accessible_attributes from Model, according to the answer I tried

def attr_names    [user_id, last_name, first_name, last_name_kana, first_name_kana, created_at,created_by, updated_at, updated_by, del_flag]  end    def self.import(file)    spreadsheet = open_spreadsheet(file)    header = spreadsheet.row(1)    (2..spreadsheet.last_row).each do |i|      row = Hash[[header, spreadsheet.row(i)].transpose]      user = find_by(user_id: row["user_id"]) || new      user.attributes = row.to_hash.slice(*attr_names)      user.save!    end  end    def self.open_spreadsheet(file)    case File.extname(file.original_filename)    when ".csv" then Roo::CSV.new(file.path, csv_options: {encoding: "SJIS"})    when ".xls" then Roo::Excel.new(file.path, nil, :ignore)    when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)    else raise "Unknown file type: #{file.original_filename}"    end  end   

Still getting same error, only this time it is undefined local variable or method 'attr_names' . Thanks in advance

Rails Datatable : jquery is not defined

Posted: 12 Aug 2016 04:05 AM PDT

Hey everyone I´m using bootstrap and other js lib in my rails app. This app is deployed on heroku so everything works well on local but when I deploy it I got this error:

ReferenceError: jQuery is not defined for

https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js. and

https://cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js

this how i got this in my application.htnl.erb

<%= javascript_include_tag 'application' %>  <script type="text/javascript" language="javascript" src="https://npmcdn.com/leaflet@0.7.7/dist/leaflet.js"></script>  <script type="text/javascript" language="javascript"  src="https://www.mapquestapi.com/sdk/leaflet/v2.s/mq-map.js?key=8HXCZd5uZivtElG97s8mEH4AFxyGe4nV"></script>  <script type="text/javascript" language="javascript" src="https://www.mapquestapi.com/sdk/leaflet/v2.s/mq-routing.js?key=8HXCZd5uZivtElG97s8mEH4AFxyGe4nV"></script>  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>  <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>    <%= yield :javascript %>  

If someone know why this is not worcking like on local tell me !

Two one-to-many relationships in Ruby-On-Rails

Posted: 12 Aug 2016 05:17 AM PDT

I have 2 models within Rails, each path has a To field and a From field, both of which reference Location Id but I can't seem to get the relationships set up properly. Any help would be appreciated. I am using Rails 4.2.6.

class Location < ActiveRecord::Base      #Fields - id, name, description, latitude, longitude    end  

and

class Path < ActiveRecord::Base      #Fields - id, from, to, distance        # belongs_to :from_location, class_name: 'Location', foreign_key: 'from'      # belongs_to :to_location, class_name: 'Location', foreign_key: 'to'        # belongs_to :from_location, class_name: 'Location'      # belongs_to :to_location, class_name: 'Location'  end  

How to log db output in rails console?

Posted: 12 Aug 2016 04:19 AM PDT

I am looking for a way to log not only query itself (like select * from users where...) but also result of the query.

for example:

I asked for User model in a query and I want to see what was returned from the database, something like: {user_id: 30, email: 'email@example.com', name: 'whatever'}.

1 comment: