Friday, November 11, 2016

Rails, Ajax, jQuery - Can't make to render changes without page refresh | Fixed issues

Rails, Ajax, jQuery - Can't make to render changes without page refresh | Fixed issues


Rails, Ajax, jQuery - Can't make to render changes without page refresh

Posted: 11 Nov 2016 07:45 AM PST

I'm using Ajax and jQuery to display changes after user adds products to cart. I use it in two places and one is working fine - when user on products page, after he adds product I display number of added products and total price in navbar (using create action) But cant make same feature on Cart page - there users can increase or decrease number of products (using increase and decrease actions)

App models: Cart has_many :line_items Product has_many :line_items LineItem belongs_to :cart, belongs_to :product

This works fine

application.html.erb:

<%= link_to @cart do %>      Your cart: <i class="glyphicon glyphicon-shopping-cart"></i>      <span id="number"><strong><%= @cart.line_items.map { |i| i[:quantity] }.sum %></span></strong> pcs.      Total: <span id="price"><strong><%= number_to_currency(@cart.line_items.map { |i| i.total_price }.sum, :unit => "€", separator: ",", format: "%n %u") %></strong></span>  <% end %>  

create.js.erb (in views/line_items folder):

$('#notice').hide();    $('#number').html("<strong><%= @cart.line_items.map { |i| i[:quantity] }.sum %></strong>")  $('#price').html("<strong><%= number_to_currency(@cart.line_items.map { |i| i.total_price }.sum, :unit => "€", separator: ",", format: "%n %u") %></strong>")  

line_items_controller.rb:

  def create      product = Product.find(params[:product_id])      @line_item = @cart.add_product(product)        respond_to do |format|        if @line_item.save          format.html { redirect_to :back }          format.js          format.json { render :show, status: :created, location: @line_item }        else          format.html { render :new }          format.json { render json: @line_item.errors, status: :unprocessable_entity }        end      end    end  

index.html.erb (store/products page):

<div class="col-xs-12 col-md-6">      <%= button_to 'Add to Cart', line_items_path(product_id: product),          class: 'btn btn-success', remote: true %>  </div>  

This does not work:

_line_item.html.erb (rendering this into _cart.html.erb):

  <tbody>        <...>        <td data-th="Quantity">          <span id="number"><%= line_item.quantity %></span>        </td>        <...>          <td><%= link_to "-", decrease_line_item_path(product_id: line_item.product), remote: true %></td>          <td><%= link_to "+", increase_line_item_path(product_id: line_item.product), remote: true %></td>        </td>      </tr>    </tbody>  

increase.js.rb / decrease.js.rb (views/line_items):

$('#number').html("<%= line_item.quantity %>")  

line_items_controller.rb:

  def decrease      product = Product.find(params[:product_id])      @line_item = @cart.remove_product(product)        respond_to do |format|        if @line_item.save          format.html { redirect_to cart_path, notice: 'Line item was successfully updated.' }          format.js          format.json { render :show, status: :ok, location: @line_item }        else          format.html { render :edit }          format.json { render json: @line_item.errors, status: :unprocessable_entity }        end      end    end      def increase      product = Product.find(params[:product_id])      @line_item = @cart.add_product(product)        respond_to do |format|        if @line_item.save          format.html { redirect_to cart_path, notice: 'Line item was successfully updated.' }          format.js          format.json { render :show, status: :ok, location: @line_item }        else          format.html { render :edit }          format.json { render json: @line_item.errors, status: :unprocessable_entity }        end      end    end  


line_items_controller.rb (full):

class LineItemsController < ApplicationController    include CurrentCart    before_action :set_cart, only: [:create, :decrease, :increase]    before_action :set_line_item, only: [:show, :edit, :update, :destroy]      def create      product = Product.find(params[:product_id])      @line_item = @cart.add_product(product)        respond_to do |format|        if @line_item.save          format.html { redirect_to :back }          format.js          format.json { render :show, status: :created, location: @line_item }        else          format.html { render :new }          format.json { render json: @line_item.errors, status: :unprocessable_entity }        end      end    end      def update      respond_to do |format|        if @line_item.update(line_item_params)          format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }          format.json { render :show, status: :ok, location: @line_item }        else          format.html { render :edit }          format.json { render json: @line_item.errors, status: :unprocessable_entity }        end      end    end      def destroy      @line_item.destroy      respond_to do |format|        format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }        format.json { head :no_content }      end    end      def decrease      product = Product.find(params[:product_id])      @line_item = @cart.remove_product(product)        respond_to do |format|        if @line_item.save          format.html { redirect_to cart_path, notice: 'Line item was successfully updated.' }          format.js          format.json { render :show, status: :ok, location: @line_item }        else          format.html { render :edit }          format.json { render json: @line_item.errors, status: :unprocessable_entity }        end      end    end      def increase      product = Product.find(params[:product_id])      @line_item = @cart.add_product(product)        respond_to do |format|        if @line_item.save          format.html { redirect_to cart_path, notice: 'Line item was successfully updated.' }          format.js          format.json { render :show, status: :ok, location: @line_item }        else          format.html { render :edit }          format.json { render json: @line_item.errors, status: :unprocessable_entity }        end      end    end      private      def set_line_item        @line_item = LineItem.find(params[:id])      end        def line_item_params        params.require(:line_item).permit(:product_id)      end  end  

cart.rb:

class Cart < ApplicationRecord    has_many :line_items, dependent: :destroy      def add_product(product)      current_item = line_items.find_by(product_id: product.id)      if current_item        current_item.quantity += 1      else        current_item = line_items.build(product_id: product.id)      end      current_item    end      def remove_product(product)      current_item = line_items.find_by(product_id: product.id)      if current_item.quantity > 1        current_item.quantity -= 1      elsif current_item.quantity = 1        current_item.destroy      end      current_item    end      def total_price      line_items.to_a.sum { |item| item.total_price }    end  end  

routes.rb:

  resources :line_items do      get 'decrease', on: :member      get 'increase', on: :member    end  

Unexpected token error while pushing to heroku for the first time

Posted: 11 Nov 2016 07:39 AM PST

I am pushing a rails app on heroku for the first time and got this error:

    C:\Sites\zunosys>git push heroku master  Counting objects: 429, done.  Delta compression using up to 2 threads.  Compressing objects: 100% (421/421), done.  Writing objects: 100% (429/429), 13.03 MiB | 48.00 KiB/s, done.  Total 429 (delta 35), 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: ###### WARNING:  remote:        Removing `Gemfile.lock` because it was generated on Windows.  remote:        Bundler will do a full resolve so native gems are handled properl  y.  remote:        This may result in unexpected gem versions being used in your app  .  remote:        In rare occasions Bundler may not be able to resolve your depende  ncies at all.  remote:        https://devcenter.heroku.com/articles/bundler-windows-gemfile  remote:  remote: -----> Installing dependencies using bundler 1.11.2  remote:        Running: bundle install --without development:test --path vendor/  bundle --binstubs vendor/bundle/bin -j4  remote:        Fetching gem metadata from http://rubygems.org/...........  remote:        Fetching version metadata from http://rubygems.org/...  remote:        Fetching dependency metadata from http://rubygems.org/..  remote:        Resolving dependencies....  remote:        Installing i18n 0.7.0  remote:        Installing rake 11.3.0  remote:        Installing json 1.8.3 with native extensions  remote:        Installing minitest 5.9.1  remote:        Installing thread_safe 0.3.5  remote:        Installing builder 3.2.2  remote:        Installing mini_portile2 2.1.0  remote:        Installing erubis 2.7.0  remote:        Installing rack 1.6.5  remote:        Installing mime-types-data 3.2016.0521  remote:        Installing arel 6.0.3  remote:        Installing execjs 2.7.0  remote:        Using bundler 1.11.2  remote:        Installing coffee-script-source 1.10.0  remote:        Installing sass 3.4.22  remote:        Installing thor 0.19.1  remote:        Installing concurrent-ruby 1.0.2  remote:        Installing multi_json 1.12.1  remote:        Installing pg 0.19.0 with native extensions  remote:        Installing rdoc 4.3.0  remote:        Installing tilt 2.0.5  remote:        Installing turbolinks-source 5.0.0  remote:        Installing tzinfo 1.2.2  remote:        Installing nokogiri 1.6.8.1 with native extensions  remote:        Installing mime-types 3.1  remote:        Installing autoprefixer-rails 6.5.3  remote:        Installing uglifier 3.0.3  remote:        Installing rack-test 0.6.3  remote:        Installing coffee-script 2.4.1  remote:        Installing sprockets 3.7.0  remote:        Installing bootstrap-sass 3.2.0.2  remote:        Installing turbolinks 5.0.1  remote:        Installing mail 2.6.4  remote:        Installing loofah 2.0.3  remote:        Installing rails-html-sanitizer 1.0.3  remote:        Installing sdoc 0.4.2  remote:        Installing activesupport 4.2.7  remote:        Installing globalid 0.3.7  remote:        Installing rails-deprecated_sanitizer 1.0.3  remote:        Installing activemodel 4.2.7  remote:        Installing activejob 4.2.7  remote:        Installing rails-dom-testing 1.0.7  remote:        Installing jbuilder 2.6.0  remote:        Installing actionview 4.2.7  remote:        Installing activerecord 4.2.7  remote:        Installing actionpack 4.2.7  remote:        Installing actionmailer 4.2.7  remote:        Installing sprockets-rails 3.2.0  remote:        Installing railties 4.2.7  remote:        Installing coffee-rails 4.1.1  remote:        Installing sass-rails 5.0.6  remote:        Installing jquery-rails 4.2.1  remote:        Installing rails 4.2.7  remote:        Bundle complete! 15 Gemfile dependencies, 53 gems now installed.  remote:        Gems in the groups development and test were not installed.  remote:        Bundled gems are installed into ./vendor/bundle.  remote:        Bundle completed (25.72s)  remote:        Cleaning up the bundler cache.  remote: -----> Preparing app for Rails asset pipeline  remote:        Running: rake assets:precompile  remote:        rake aborted!  remote:        ExecJS::RuntimeError: SyntaxError: Unexpected token: operator (<)   (line: 22736, col: 0, pos: 774817)  remote:        Error  remote:        at new JS_Parse_Error (/tmp/execjs20161111-933-omsknejs:3623:1194  8)  remote:        at js_error (/tmp/execjs20161111-933-omsknejs:3623:12167)  remote:        at croak (/tmp/execjs20161111-933-omsknejs:3623:22038)  remote:        at token_error (/tmp/execjs20161111-933-omsknejs:3623:22175)  remote:        at unexpected (/tmp/execjs20161111-933-omsknejs:3623:22263)  remote:        at expr_atom (/tmp/execjs20161111-933-omsknejs:3623:31244)  remote:        at maybe_unary (/tmp/execjs20161111-933-omsknejs:3624:1752)  remote:        at expr_ops (/tmp/execjs20161111-933-omsknejs:3624:2523)  remote:        at maybe_conditional (/tmp/execjs20161111-933-omsknejs:3624:2615)    remote:        at maybe_assign (/tmp/execjs20161111-933-omsknejs:3624:3058)  remote:        at expression (/tmp/execjs20161111-933-omsknejs:3624:3384)  remote:        at simple_statement (/tmp/execjs20161111-933-omsknejs:3623:25942)    remote:        at /tmp/execjs20161111-933-omsknejs:3623:23662  remote:        at /tmp/execjs20161111-933-omsknejs:3623:22954  remote:        new JS_Parse_Error ((execjs):3623:11948)  remote:        js_error ((execjs):3623:12167)  remote:        croak ((execjs):3623:22038)  remote:        token_error ((execjs):3623:22175)  remote:        unexpected ((execjs):3623:22263)  remote:        expr_atom ((execjs):3623:31244)  remote:        maybe_unary ((execjs):3624:1752)  remote:        expr_ops ((execjs):3624:2523)  remote:        maybe_conditional ((execjs):3624:2615)  remote:        maybe_assign ((execjs):3624:3058)  remote:        expression ((execjs):3624:3384)  remote:        simple_statement ((execjs):3623:25942)  remote:        (execjs):3623:23662  remote:        (execjs):3623:22954  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/execjs-2.7.0/lib/execjs/external_runtime.rb:39:in `exec'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/execjs-2.7.0/lib/execjs/external_runtime.rb:21:in `eval'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/execjs-2.7.0/lib/execjs/external_runtime.rb:46:in `call'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/uglifier-3.0.3/lib/uglifier.rb:182:in `run_uglifyjs'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/uglifier-3.0.3/lib/uglifier.rb:144:in `compile'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/uglifier_compressor.rb:52:in `call'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/uglifier_compressor.rb:28:in `call'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/processor_utils.rb:75:in `call_processor'    remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/processor_utils.rb:57:in `block in call_p  rocessors'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/processor_utils.rb:56:in `reverse_each'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/processor_utils.rb:56:in `call_processors  '  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/loader.rb:134:in `load_from_unloaded'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/loader.rb:60:in `block in load'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/loader.rb:317:in `fetch_asset_from_depend  ency_cache'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/loader.rb:44:in `load'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/cached_environment.rb:20:in `block in ini  tialize'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/cached_environment.rb:47:in `yield'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/cached_environment.rb:47:in `load'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/base.rb:66:in `find_asset'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/base.rb:73:in `find_all_linked_assets'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/manifest.rb:142:in `block in find'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:114:in `block (2 levels) in log  ical_paths'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:228:in `block in stat_tree'    remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:212:in `block in stat_direc  tory'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:209:in `each'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:209:in `stat_directory'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/path_utils.rb:227:in `stat_tree'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:105:in `each'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:105:in `block in logical_paths'    remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:104:in `each'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/legacy.rb:104:in `logical_paths'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/manifest.rb:140:in `find'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/sprockets/manifest.rb:185:in `compile'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:68:in `block (3 level  s) in define'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-3.7.0/lib/rake/sprocketstask.rb:147:in `with_logger'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:67:in `block (2 level  s) in define'  remote:        /tmp/build_f0be564707a7bc4a54cf1cbbf6043492/vendor/bundle/ruby/2.  2.0/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'  remote:        Tasks: TOP => assets:precompile  remote:        (See full trace by running task with --trace)  remote:  !  remote:  !     Precompiling assets failed.  remote:  !  remote:  !     Push rejected, failed to compile Ruby app.  remote:  remote:  !     Push failed  remote: Verifying deploy...  remote:  remote: !       Push rejected to zunosys.  remote:  To https://git.heroku.com/zunosys.git   ! [remote rejected] master -> master (pre-receive hook declined)  error: failed to push some refs to 'https://git.heroku.com/zunosys.git'  

to understand the issue i did a rake assets:precompile

C:\Sites\zunosys>rake assets:precompile  rake aborted!  Sass::SyntaxError: Undefined mixin 'border-radius'.  C:/Sites/zunosys/app/assets/stylesheets/_accordion.scss:6:in `border-radius'  C:/Sites/zunosys/app/assets/stylesheets/_accordion.scss:6  Tasks: TOP => assets:precompile  (See full trace by running task with --trace)  

Rails: Ransack Gem using dropdown - "undefined method name" error

Posted: 11 Nov 2016 07:36 AM PST

I am using the Ransack gem to create a filter form for my table.

In my controller (I am taking the filter options from another table): homeworks_controller:

...     @q = Homework.search(params[:q])          @sub = Homework.find_by_sql("SELECT subject FROM classmodules GROUP BY subject").map &:subject          @q.build_condition if @q.conditions.empty?          @q.build_sort if @q.sorts.empty?  ...  

In my view

<%= search_form_for @q do |f| %>       <%= f.select :subject_eq, @sub %>      <%= f.submit %>    <% end %>  

Models

        classmodule.rb          has_many :homeworks, :class_name => 'Homework'            homework.rb          belongs_to :classmodule, :class_name => 'Classmodule', :foreign_key => :subject      

I get "undefined method `name' for nil:NilClass" as an error.

I searched for an answer but nothing solid for this and tried some suggested solutions. I'm stuck, any ideas? Thanks

static error pages from an engine

Posted: 11 Nov 2016 07:25 AM PST

I have an engine I'm using in a suite of apps to share assets, layout, MVCs and helpers. I'd like to add error pages to that list, what's the easiest way to go about this for static pages? Ideally, I'd like each app using the engine to serve up the error pages in my engine's public/ rather than the main app's public/.

Two step confirmation with Devise 4.2 and Rails 5

Posted: 11 Nov 2016 07:23 AM PST

I'm developing an rails API and I'm facing the problem of making, with devise and devise_token_auth a two steps confirmation for user registration specified here. To put more context in this post, what I'm trying to accomplish is give the ability to create a standard user by an admin only inputing the user email, and then sending an email to with an URL with a confirmation token in it so he then input his password and password confirmationm so he can finally finish creating the user.

So it appears that the documentation specified in the post from above isn't too much updated as the most updated post is for Rails 4 with Devise 3.X. I'm using Rails 5 and Devise 4.2, not totally sure if that affects something, but I tried to do what specified and, of course, didn't work.

I'll be glad to hear some advices on this. I've been researching and there's not too much documentation about it, also because I have the complexity of using devise_token_auth, not only devise.

get the latest version from an array in ruby

Posted: 11 Nov 2016 07:46 AM PST

I have an array of version numbers called unique_versions that keeps on increasing :

1.7.16  1.7.14  1.7.13  1.7.12  1.7.9  1.7.7  1.7.5  1.7.4  1.7.2  1.6.2  1.2.1  1.2.0  1.1.0  0.0.1  

and I need to get the latest(1.7.16) from the array. What the most elegant ruby way of doing it ? I get this array by the following code :

require "json"  require "open-uri"  require 'openssl'    string_object = open("https://xxx", :http_basic_authentication=>["xxx"], :ssl_verify_mode=>OpenSSL::SSL::VERIFY_NONE)  json_file = JSON.parse(string_object.read)  version_array = Array.new  json_file["results"].each do |version|      version_array.push(version["version"].sub /-.*$/, '')  end  unique_versions=(version_array.uniq)  

Rails 4: Masonry gem

Posted: 11 Nov 2016 07:42 AM PST

I've installed the Masonry gem both using my gemfile:

gem 'masonry-rails'  

...as well as from the console:

$ gem install masonry-rails  Successfully installed masonry-rails-0.2.4  Parsing documentation for masonry-rails-0.2.4  Installing ri documentation for masonry-rails-0.2.4  Done installing documentation for masonry-rails after 1 seconds  1 gem installed  

I've restarted my app, but when I call:

//= require masonry/masonry  

in my application.js, I see the error:

couldn't find file 'masonry/masonry' with type 'application/javascript'  

...any thought on why this might occur? I've used the CDN successfully, but wanted to switch over to the gem. I've also tried requiring masonry rather than masonry/masonry with no avail.

Rails nested form with unknown columns

Posted: 11 Nov 2016 07:03 AM PST

I'm creating an admin interface where the admin (of a company) can add custom fields to their employees.

Example:

Models:

  • Employee: Basic info like name, contact info, etc (has_many employee_field_values)
  • EmployeeFields: These are the dynamic ones the admin can add (every company has different needs, it could be anything), lets say favorite_food
  • EmployeeFieldValues: The actual values based on the fields above, say pizza (belongs_to both models above)

What's a smart way of adding the EmployeeFieldValues fields while editing an employee?

I'm trying something simple like this, but not sure if I like it

# Controller  @custom_fields = EmployeeFields.all    # View  <%= form_for(@employee) do |f| %>    <%= f.text_field :first_name %>      <% @custom_fields.each do |custom_field| %>      <%= custom_field.name %>      <%= text_field_tag "employee_field_values[#{custom_field.name}]" %>    <% end %>      <%= f.submit :save %>  <% end %>  

And then when updating, params[:employee_field_values] gives this:

<ActionController::Parameters {"favorite_food"=>"pizza"}>  

So, not sure if this is a good direction, also I'm not sure how to handle future edits to an employee's custom_fields if they change.

RSpec and Factory Girl - Error with datetime field

Posted: 11 Nov 2016 06:59 AM PST

I'm with the following problem:

Environment: Ruby: 2.3.1 and Rails 5.0.0.1

I'm trying to validate a datetime field with RSpec and Factory Girl.

I got this error:

expected: "2016-11-11 13:30:31 UTC"  (From Factory Girl)       got: "2016-11-11T13:30:31.218Z" (From database)  

My code:

klass_object = FactoryGirl.create(:character)

klass = Character

RSpec.shared_examples 'API GET #index' do |klass|    before { get :index, params: params, accept: Mime[:json] }        it "returns a list of #{klass.to_s.underscore.pluralize}" do      object_array = json(response.body)        klass_attributes = klass.attribute_names.without("id", "created_at", "updated_at").map(&:to_sym)        klass_attributes.each do |attribute|        object_array.each do |object|          expect(object[attribute].to_s).to eq(klass_object[attribute].to_s)        end      end    end    ...  end  

Factory:

FactoryGirl.define do    factory :character do      marvel_id { Faker::Number.number(6).to_i }      name { Faker::Superhero.name }      description { Faker::Hipster.paragraphs(1) }      modified { Faker::Date.between(DateTime.now - 1, DateTime.now) }        factory :invalid_character do        id ''        name ''        marvel_id ''        modified ''      end    end  

end

How can I correct this problem?

Thanks for your help.

NoMethodError - Calculation in Rails Model

Posted: 11 Nov 2016 06:49 AM PST

I have an item model. In that model I need to be able to calculate the profit of a product. However, if I just bought that item it obviously has not been purchased yet and the values for sold_for, fees, and shipping will be empty. If there are no values entered I get a undefined method-' for nil:NilClasserror. I triedrescue NoMethodError`, but then it would not calculate the profit. Is there a way to avoid the error and also have my calculation work?

items.rb

class Item < ActiveRecord::Base    def profit_calc      sold_for - bought_for - fees - shipping    end      def self.purchase_total      sum(:bought_for)    end      def self.fee_total      sum(:fees)    end      def self.shipping_total      sum(:shipping)    end      def self.sales_total      sum(:sold_for)    end      def self.profit_total      sum(:sold_for) - sum(:bought_for) - sum(:fees) - sum(:shipping)    end      scope :visible, -> { where(sold: false) }    scope :sold, -> { where(sold: true) }  end  

html.erb:

<td><%= number_to_currency(item.profit_calc) %></td>  

Elasticsearch Rails as_indexed_json vs mappings

Posted: 11 Nov 2016 07:31 AM PST

I am using the Elasticsearch Rails gem and I am using two things in my model:

def as_indexed_json    end  

and

settings index: { number_of_shards: 1 } do    mapping dynamic: 'false' do      end  end   

I have read the documentation and I am not understanding what the purposes of each of these are. What I am trying to figure out is are these used for searching the indexed data or for creating the indexed data?

TinyMCE - have to refresh the page

Posted: 11 Nov 2016 06:21 AM PST

When I navigate to a page with TinyMCE it displays regular textareas until I refresh the page because of turbolinks. This is a pretty well-documented issue and people generally recommend some form of the following:

$(document).on('page:change', function () {      <code here>  });   

I've tried every variation on this to no avail.

Search logic in ruby on rails 4.0

Posted: 11 Nov 2016 07:43 AM PST

Well when we are implementing simple search its something like (searching for a song):

Model:

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

but when the query is something like James TW when you love someone and the name of the song is when you love some James TW it doesnt return anything. So what do I do about that hat the correct logic for that?

@user.reload not working as expected (change the year to 2000)

Posted: 11 Nov 2016 06:57 AM PST

Hi I`m following the Michael Hartl tutorial and I came across strange behaviour.

In chapter 12 Password reset, password_reset_controller, create action looks like this:

  def create      @user = User.find_by(email: params[:password_reset][:email].downcase)       if @user             @user.create_reset_digest           @user.send_password_reset_email        flash[:info] = 'Email sent with password reset instructions'            redirect_to root_url             else        flash.now[:danger] = 'Email address not found'        render 'new'      end    end  

And the create_reset_digest method looks like this:

def create_reset_digest      self.reset_token = User.new_token      update_attribute(:reset_digest, User.digest(reset_token))      update_attribute(:reset_sent_at, Time.zone.now)  end  

I used a byebug to monitor changes and came across a strange thing:

When I try byebug at the end of the create action I got this result:

 #<User id: 762146111, ..., reset_sent_at: 2016-11-11 13:47:00 UTC>  

But when I try to see what was saved after @user.reload, I get:

#<User id: 762146111, ..., reset_sent_at: "2000-01-01 13:47:00">  

Why is the attribute reser_sent_at switching to year 2000-01-01?

Deprecation Warning About Mass Assignment Rails 4.0

Posted: 11 Nov 2016 05:50 AM PST

I am upgrading an app to 4.0 and using ruby-2.2.5. I am down to a couple of Deprecation Warnings, which appear when I run >> bundle exec rake.

One of the warnings:

DEPRECATION WARNING: Model based mass assignment security has been extracted out of Rails into a gem.   Please use the new recommended protection model for params or add `protected_attributes` to your Gemfile to use the old one.    To disable this message remove the `whitelist_attributes` option from your `config/application.rb` file   and any `mass_assignment_sanitizer` options from your `config/environments/*.rb` files.    See http://guides.rubyonrails.org/security.html#mass-assignment for more information.  

I understand what this about and I have gone through all my models looking for and removing 'attr_accessible'. I have gone through all my controllers and added a method for strong_params, which I call in my 'create' and 'update' actions. We are not using 'whitelist_attributes' or any 'mass_assignment_sanitizer' options. And, all my spec tests are passing.

My Questions is, Would this warning be just a standard output or would it be from rails seeing something I am not? Ideas?

Much appreciated

"Certificate verify failed" while using http://rubygems.org instead of https

Posted: 11 Nov 2016 05:42 AM PST

I used to get a certificate verification error when I used the https:/rubygems.org.

A workaround was suggested: remove the "s" (so I end up using http instead of https). It worked for some time but today after starting a new rails application rails new 'filename' I got the same certificate validation error:

Gem::RemoteFetcher::FetchError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed (https://rubygems.org/gems/mime-types-data-3.2016.0521.gem) An error occurred while installing mime-types-data (3.2016.0521), and Bundler cannot continue. Make sure that gem install mime-types-data -v '3.2016.0521' succeeds before bundling.

I typed gem sources only to find that https://rubygems.org doesn't even exist.

    $ gem sources  *** CURRENT SOURCES ***    http://rubygems.org  

I go to the gemfile and I find

source 'https://rubygems.org'  

What could be the problem?

How to reference an image within HTML tag in Rails 4

Posted: 11 Nov 2016 04:29 AM PST

I understand that rails assets eg. an image in assets/images/ get a cache helper number appended to them ie. background.jpg may become background77bfb376c1e.jpg and therefore, a helper must be used to reference them e.g.

asset-url("background.png", image)  

However.. How could I reference background.jpg in a HTML tag such as this:

<header class="pt100 pb100 parallax-window-2" data-image-src="background.jpg">  

? Apologies in advance if the solutions is obvious ...

Pass table name as parameter to ruby method

Posted: 11 Nov 2016 05:11 AM PST

I have N number of tables and N number of functions. All functions have same code only table name changes. Can I make a common function to be used by all of these function.

Something like this

def funcN    common_func(tableN)  end    private    def common_func(tablename)    "Some Code"  end  

I know there may be multiple ways.. What are the possible ways to do it?

How to create a custom processor for audio files in Ruby on Rails(5) with Paperclip

Posted: 11 Nov 2016 03:51 AM PST

So I'm trying to convert mp3 files into .flac with Paperclip custom processors and ffmpeg. The following code runs the ffmpeg command and creates a temporary flac file. However, it is not saved? Currently only the original file is saved. What am I missing here?

class AudioFile < ApplicationRecord    has_attached_file :raw_audio, processors: [:custom], styles: { original: {}}  

the custom processor

module Paperclip   class Custom < Processor      def initialize(file, options = {}, attachment = nil)      super      @file = file      @basename = File.basename(@file.path)      @format = options[:format] || 'flac'      @params = options[:params] || '-y -i'     end      def make      source = @file      output = Tempfile.new([@basename, ".#{@format}"])      begin        parameters = [@params, ':source',':dest'].join(' ')        Paperclip.run('ffmpeg', parameters, :source => File.expand_path(source.path), :dest => File.expand_path(output.path), :sample_rate => @sample_rate, :bit_rate => @bit_rate)      end     output    end     end  end  

Rails. Undefined method `remove_product' for nil:NilClass

Posted: 11 Nov 2016 04:04 AM PST

App models: Cart has_many :line_items Product has_many :line_items LineItem belongs_to :cart, belongs_to :product

If the same product being added in the cart multiple times, I count that number in cart.rb:

  def add_product(product)      current_item = line_items.find_by(product_id: product.id)      if current_item        current_item.quantity += 1      else        current_item = line_items.build(product_id: product.id)      end      current_item    end  

Now I want to give user ability to increase / decrease that number. Increasing going well:

line_items_controller.rb:

  def create      product = Product.find(params[:product_id])      @line_item = @cart.add_product(product)        respond_to do |format|        if @line_item.save          format.html { redirect_to store_index_url }          format.js   { @highlited_item = @line_item }          format.json { render :show, status: :created, location: @line_item }        else          format.html { render :new }          format.json { render json: @line_item.errors, status: :unprocessable_entity }        end      end    end  

line_item.html.erb:

<td><%= link_to "+", line_items_path(product_id: line_item.product), method: :post, remote: true %></td>  

But decreasing doesn't go so well. My plan is:

cart.rb (not sure how this would work, since here that error of undefined method add_product fires up):

  def remove_product(product)      current_item = line_items.find_by(product_id: product.id)      if current_item.quantity > 1        current_item.quantity -= 1      elsif current_item.quantity = 1        current_item.destroy      end      current_item unless current_item.nil    end  

line_items_controller.rb:

  def decrease      product = Product.find(params[:product_id])      @line_item = @cart.remove_product(product)    end  

Full line_items_controller.rb:

class LineItemsController < ApplicationController        include CurrentCart        before_action :set_cart, only: [:create]        before_action :set_line_item, only: [:show, :edit, :update, :destroy]          def index          @line_items = LineItem.all        end          def show        end          def new          @line_item = LineItem.new        end          def edit        end          def create          product = Product.find(params[:product_id])          @line_item = @cart.add_product(product)            respond_to do |format|            if @line_item.save              format.html { redirect_to store_index_url }              format.js   { @highlited_item = @line_item }              format.json { render :show, status: :created, location: @line_item }            else              format.html { render :new }              format.json { render json: @line_item.errors, status: :unprocessable_entity }            end          end        end          def update          respond_to do |format|            if @line_item.update(line_item_params)              format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }              format.json { render :show, status: :ok, location: @line_item }            else              format.html { render :edit }              format.json { render json: @line_item.errors, status: :unprocessable_entity }            end          end        end          def destroy          @line_item.destroy          respond_to do |format|            format.html { redirect_to line_items_url, notice: 'Line item was successfully destroyed.' }            format.json { head :no_content }          end        end            private          def set_line_item            @line_item = LineItem.find(params[:id])          end            def line_item_params            params.require(:line_item).permit(:product_id)          end      end  

Why I get that undefined method remove_product in decrease action?

Many thanks!

undefined method `priority_countries=' for Carmen:Module (NoMethodError)

Posted: 11 Nov 2016 04:02 AM PST

New to Rails and Ruby on Rails,

the code in file /host_share/my_application/config/initializers/countries.rb

Carmen.priority_countries = %w(US CA MX)  Carmen.excluded_countries = ["AC", "AF", "AX", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU",                                  "AZ", "BS", "BH", "BD", "BB", "BY", "BZ", "BJ", "BL", "BM", "BT", "BO", "BA", "BW", "BV",                                  "BR", "IO", "BN", "BG", "BF", "BI", "BQ", "KH", "CM", "CV", "KY", "CF", "TD", "CL", "CN",                                  "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "CI", "HR", "CU", "CW", "DJ",                                  "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET",  "FO", "FJ", "GF",                                  "PF", "TF", "GA", "GM", "GE", "GH", "GI", "GD", "GP", "GU", "GT", "GG",                                  "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK", "HU", "IN", "ID", "IR", "IQ",                                  "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KP", "KR", "KV", "KW", "KG",                                  "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "MO", "MK", "MG", "MW", "MY", "MV",                                  "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "FM", "MD", "MN", "MF", "ME", "MA",                                  "MZ", "MM", "NA", "NR", "NP", "AN", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP",                                  "NO", "OM", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "QA",                                  "RE", "RO", "RU", "RW", "SH", "KN", "LC", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS",                                  "SC", "SL", "SG", "SK", "SI", "SB", "SO", "ZA", "GS", "LK", "SD", "SR", "SJ", "SZ",                                  "SX", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN", "TR", "TM",                                  "TC", "TV", "UG", "UA", "AE", "UM", "UY", "UZ", "VU", "VE", "VN",                                  "WF", "EH", "YE", "ZM", "ZW", "SS", "TA"]  

trying to upgrade old rails 3.2.19 application to 4.0.13 (latest of 4.0.x), after doing all required changes in code my application gets stuck at

/host_share/my_application/config/initializers/countries.rb:4:in `<top (required)>': undefined method `priority_countries=' for Carmen:Module (NoMethodError)      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.13/lib/active_support/dependencies.rb:223:in `load'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.13/lib/active_support/dependencies.rb:223:in `block in load'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.13/lib/active_support/dependencies.rb:214:in `load_dependency'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.13/lib/active_support/dependencies.rb:223:in `load'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/engine.rb:609:in `block (2 levels) in <class:Engine>'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/engine.rb:608:in `each'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/engine.rb:608:in `block in <class:Engine>'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/initializable.rb:30:in `instance_exec'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/initializable.rb:30:in `run'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/initializable.rb:55:in `block in run_initializers'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:150:in `block in tsort_each'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:183:in `block (2 levels) in each_strongly_connected_component'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:210:in `block (2 levels) in each_strongly_connected_component_from'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:219:in `each_strongly_connected_component_from'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:209:in `block in each_strongly_connected_component_from'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/initializable.rb:44:in `each'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/initializable.rb:44:in `tsort_each_child'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:203:in `each_strongly_connected_component_from'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:182:in `block in each_strongly_connected_component'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:180:in `each'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:180:in `each_strongly_connected_component'      from /home/vagrant/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/tsort.rb:148:in `tsort_each'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/initializable.rb:54:in `run_initializers'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/application.rb:215:in `initialize!'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/railtie/configurable.rb:30:in `method_missing'      from /host_share/my_application/config/environment.rb:5:in `<top (required)>'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.13/lib/active_support/dependencies.rb:229:in `require'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.13/lib/active_support/dependencies.rb:229:in `block in require'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.13/lib/active_support/dependencies.rb:214:in `load_dependency'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/activesupport-4.0.13/lib/active_support/dependencies.rb:229:in `require'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/application.rb:189:in `require_environment!'      from /home/vagrant/.rvm/gems/ruby-2.0.0-p481/gems/railties-4.0.13/lib/rails/commands.rb:44:in `<top (required)>'      from script/rails:6:in `require'      from script/rails:6:in `<main>'  

UPDATE: This code Carmen.priority_countries is the part of carmen version 0.2.8 and not anymore supported in latest version,

So the new question is how do I change my code to make it work accordingly?

Ruby: stringA.gsub(/\s+/, '') versus stringA.strip

Posted: 11 Nov 2016 03:31 AM PST

Say

string = "Johnny be good! And smile   :-) "  

Is there a difference between

string.gsub(/\s+/, '')  

and

string.strip  

?

If so, what is it?

Need help to configure CanCanCan for activeadmin

Posted: 11 Nov 2016 03:33 AM PST

I need help to configure CanCanCan using ActiveAdmin. I have everything else working including devise. I can restrict menus using devise but if you know the URL lets say for edit you can still edit that resource. I want to restrict a normal user from editing/creating any resources but it does not seem to work.

Active_Admin.rb

config.cancan_ability_class = ActiveAdmin::CanCanAdapter  

Ability.rb (simple out of the box)

class Ability    include CanCan::Ability      def initialize(user)      # Define abilities for the passed in user here. For example:      #        # user ||= User.new # guest user (not logged in)        if user.admin?          can :manage, Student        else          can :read, Student        end  end  end  

User model.

admin:boolean   

and if I login with a user who is not an admin i can still create/edit/delete, I just want to restrict them to read only.

Please help i am struggling with this only feature that I need to complete.

Thanks in advance

send_file: PDF seems corrupted (?) and doesn't trigger download, opens in broswer instead

Posted: 11 Nov 2016 06:01 AM PST

This is my routes.rb

resources :welcome do    get :download, :on => :collection  end  

I have tried 2 variations in my controller

First

def download    send_file("#{Rails.root}/public/assets/resources/testing.pdf", :type => "application/pdf", :disposition => "attachment")  end  

Second

def download    send_file("#{Rails.root}/public/assets/resources/#{params[:file_name]}", :type => "application/pdf", :disposition => "attachment")  end  

This is my view and i have tried 2 different link_to according to the controller action.

First

<%= link_to 'Test Paper', action: :download %>  

Second

<%= link_to 'Test Paper', action: :download, file_name: 'testing.pdf' %>  

Neither of them are working and i don't know why. I actually saw a similar SO post, but unfortunately there are no answers there.

The download doesn't trigger, it just opens the PDF in the browser, and it renders in a "corrupted" format. What am i missing?

Javascript and Rails, put code into a cycle

Posted: 11 Nov 2016 03:06 AM PST

In my app, i'm building a simple mailbox section. Idea is to use same partial for received messages and sended messages, "personalizing" the mailbox using javascript. I'm a javascript newbie.. This is my trivial partial, where @box is the list of all received or sended messages (set via controller)

<div class="container-full">    <div class="mailbox">      <div class="caption">        <% if @box.blank? %>          Non ci sono messaggi <span id="inout"></span>        <% else %>          Ci sono <%= @box.count %> messaggi <span id="inout"></span>        <% end %>      </div>      <table class="table">        <caption> Messaggi <span id="inout"></span></caption>        <thead>          <tr>            <th> <span id="invric"></span> da </th>            <th> Data di invio </th>            <th> messaggio </th>          </tr>        </thead>        <tbody><% if !@box.blank? %><% @box.each do |m| %>          <tr>            <td id="mailselector"></td>            <td> <%= m.updated_at.to_formatted_s(:short) %> </td>            <td> <%= m.mex[0, 30] %><span>...</span> </td>          </tr>          <% end %> <% end %>        </tbody>      </table>    </div>  </div>  

and this is the javascript for the received messages:

$("#contenthere").html("<%= escape_javascript(render('farmers/box')) %>");  $("#inout").html("ricevuti");  $("#invric").html("Ricevuto");  $("#mailselector").append('<%= m.sender.nick %>')  

the last line don't run because m is undefined. How can i do in the right way?

Writing test on generated text

Posted: 11 Nov 2016 03:29 AM PST

I'm replacing words in a piece of content with a rails helper to add tooltips. No problem at all and working fine, but i would like to test this helper on the exact output and because the replacement adds some unwanted formatting i find it hard to really test this helper.

original string

a piece of <a href="http://">content</a> that contains jargon1 to be replaced  

my helper replaces jargon1 with some html to render a tooltip

content.gsub!(/#{jargon.word}/i, get_node(jargon))    def get_node jargon    <<-HTML      <a href='#jargon-#{jargon.id}'        class='jargon-tip'        data-toggle='tooltip'        data-placement='top'        data-original-title='#{jargon.desc}'        rel='help'>#{jargon.word}</a>    HTML  end  

result of the string with the injected html

a piece of <a href="http://">content</a> that contains       <a href='#jargon-130'      class='jargon-tip'      data-toggle='tooltip'      data-placement='top'      data-original-title='desc for jargon 1'      rel='help'>jargon1</a>       to be replaced  

First of all there are 7 spaces between that contains and <a and i would like the html to display inline in the result but in my code i like it formatted like above to keep it readable.

My end goal would be to build a robust test on comparing the parsed string to a pre defined string. For now i only test on a piece of the string (expect(result).to include("data-original-title='desc for jargon 1'")) because of formatting issues with \n and it going to be a fragile test.

Thanks in advance!

How Do Display Uploaded Documents(pdf, doc, docx) as Text In Views

Posted: 11 Nov 2016 02:24 AM PST

I am trying to display an uploaded document as text in my views using carrierwave gem. All I have been able to get is just the url of the uploaded documents. Any ideas?

Can't install Spree

Posted: 11 Nov 2016 04:45 AM PST

trying to install Spree on Ubuntu, but I'm new to Linux systems. Below is the error message:

-desktop ~/mystore $ bundle install  Fetching gem metadata from https://rubygems.org/............  Fetching version metadata from https://rubygems.org/..  Fetching dependency metadata from https://rubygems.org/.  Resolving dependencies...  Bundler could not find compatible versions for gem "spree_core":    In Gemfile:      spree (~> 3.1.1) was resolved to 3.1.1, which depends on        spree_core (= 3.1.1)      spree (~> 3.1.1) was resolved to 3.1.1, which depends on        spree_core (= 3.1.1)      spree (~> 3.1.1) was resolved to 3.1.1, which depends on        spree_core (= 3.1.1)      spree (~> 3.1.1) was resolved to 3.1.1, which depends on        spree_core (= 3.1.1)      spree (~> 3.1.1) was resolved to 3.1.1, which depends on        spree_core (= 3.1.1)      spree_gateway (~> 3.0.0) was resolved to 3.0.0, which depends on        spree_core (~> 3.0.0)  

And all this gems is installed, below is the list:

 rails (5.0.0.1, 4.2.7.1, 4.2.6, 4.2.5)      rails-deprecated_sanitizer (1.0.3)      rails-dom-testing (2.0.1, 1.0.7)      rails-html-sanitizer (1.0.3)      railties (5.0.0.1, 4.2.7.1, 4.2.6, 4.2.5)      rake (11.3.0, 10.4.2)      ransack (1.4.1)      rb-fsevent (0.9.8)      rb-inotify (0.9.7)      rdoc (4.3.0, 4.2.1)      responders (2.3.0)      sass (3.4.22)      sass-rails (5.0.6)      sdoc (0.4.2)      select2-rails (3.5.9.1)      sixarm_ruby_unaccent (1.1.1)      spree (3.1.1, 3.0.0)      spree_api (3.1.1, 3.0.0)      spree_auth_devise (3.1.0)      spree_backend (3.1.1, 3.0.0)      spree_cmd (3.1.1, 3.0.0)      spree_core (3.1.1, 3.0.0)      spree_frontend (3.1.1, 3.0.0)      spree_gateway (3.1.0, 3.0.0)      spree_sample (3.1.1, 3.0.0)  

I tried to install different version of rails, Spree, but always the same error. Could you please help?

Rails validate format with regex

Posted: 11 Nov 2016 02:29 AM PST

In my rails app, I want to validate input on a string field containing any number of keywords (which could be more than 1 natural language word (e.g. "document number")). To recognize the individual keywords, I am entering them separated by ", " (or get their end by end of string).

For this I use

validates :keywords, presence: true, format: { with: /((\w+\s?-?\w+)(,|\z))/i, message: "please enter keywords in correct format"}

It should allow the attribute keywords (string) to contain: "word1, word2, word3 word4, word5-word6"

It should not allow the use of any other pattern. e.g. not "word1; word2;" It does incorrectly allow "word1; word2"

On rubular, this regex works; yet in my rails app it allows for example "word1; word2" or "word3; word-"

where is my error (got to say am beginner in Ruby and regex)?

How to replace routes for user model by role

Posted: 11 Nov 2016 02:08 AM PST

I have model User contain column role.

class CreateUsers < ActiveRecord::Migration[5.0]    def change      create_table :users do |t|        t.string :name        t.string :email        t.string :address        t.integer :role        t.timestamps      end    end  end  

Role contain: shop & shipper.

Routes.rb

resources :users  

And url for action show (profile): http://localhost:3000/users/1

I want change it with :role. For example: http://localhost:3000/shops/1 (if role:shop) or .../shippers/1 (if role:shipper).

i don't know how to do that. Help me pls, Thank you!

1 comment: