Tuesday, July 26, 2016

Chart.js in rails | Fixed issues

Chart.js in rails | Fixed issues


Chart.js in rails

Posted: 26 Jul 2016 08:06 AM PDT

I have discovered a problem that I, as I am new to rails and chart.js, can not solve. I want a graph that also shows data that are not in the label. Immoment I have the problem that I have a month on dates, I want only 5 labels(not 31 labels on the x-axis). Chart.js scans my data and submit only for the first 5 data listings dots in the graph but I also want to have dots between the labels. Here is my code

<canvas id="orderChartLastMonth" width="400" height="400"></canvas>      <script>        <%= foo = ((Date.today - 1.month).beginning_of_month) %>        var ctx = document.getElementById("orderChartLastMonth");        var orderChartLastMonth = new Chart(ctx, {          type: 'line',          data: {            labels: [              "<%=foo %>", "<%=foo + 1.week%>", "<%=foo + 2.week %>",              "<%=foo + 3.week%>", "<%=foo + 4.week%>"            ],            datasets: [{              label: 'Graph Orders last week',              data: <%= (foo..foo.end_of_month).map { |date| Company.graph_order(date).to_f}.inspect  %>,            }]},          options:{            legend:{              display: false            }}});      </script>  

Company.graph_order selects only the orders from that date. Can you guys recommend using chart.js or is it the worst? If you have another solution, pls write it into the comments(it has to be non-licens)

Greetings!

factory_girl linter failing because of ActionView::Template::Error

Posted: 26 Jul 2016 08:23 AM PDT

I'm in the process of working out the bugs for updating an app from rails 4.1 to rails 5. When I try to run my tests the factory_girl linter complains that some of the factories are invalid:

/Users/stephen/.rvm/gems/ruby-2.3.1@ssa/gems/factory_girl-4.7.0/lib/factory_girl/linter.rb:13:in `lint!': The following factories are invalid: (FactoryGirl::InvalidFactoryError)    * call_log - Undefined variable: "$green". (ActionView::Template::Error)  * sms_log - Undefined variable: "$green". (ActionView::Template::Error)  

etc.

This is all factory girl really gives me for a stack trace. It tells me the where the linter is called but that is it. No indication where something might be going in the view. Is there a way for me to determine this? It seems like this is going to be very difficult to debug fi I don't know where it's coming from.

Using Capybara with Webkit to select an option from a Chosen Multiselector

Posted: 26 Jul 2016 08:19 AM PDT

I have a multiselector that uses the Chosen plugin as shown below:

<%= select_tag :provinces,  options_for_select(DataHelper::all_provinces_captions.zip(DataHelper::all_provinces_ids)),  {:multiple => true, class: 'chosen-select chzn-select',   :data => {:placeholder => 'Filter Provinces/States'},   :style => "width: 100%; height: 100px;"}%>  

Here are the relevant DataHelper selection arrays:

def self.all_provinces_captions      usa_provinces_with_caption.map { |x| x.first } + canada_provinces_with_caption.map { |x| x.first }  end  def self.all_provinces_ids      usa_provinces_with_caption.map { |x| (Province.find_by name: x.first).id} + canada_provinces_with_caption.map { |x| (Province.find_by name: x.first).id }  end  def self.usa_provinces_with_caption          [["Alabama", "alabama"], ["Alaska", "alaska"], ["Arizona", "arizona"], ["Arkansas", "arkansas"], ["California", "california"], ["Colorado", "colorado"], ["Connecticut", "connecticut"], ["Delaware", "delaware"], ["District Of Columbia", "district of columbia"], ["Florida", "florida"], ["Georgia", "georgia"], ["Hawaii", "hawaii"], ["Idaho", "idaho"], ["Illinois", "illinois"], ["Indiana", "indiana"], ["Iowa", "iowa"], ["Kansas", "kansas"], ["Kentucky", "kentucky"], ["Louisiana", "louisiana"], ["Maine", "maine"], ["Maryland", "maryland"], ["Massachusetts", "massachusetts"], ["Michigan", "michigan"], ["Minnesota", "minnesota"], ["Mississippi", "mississippi"], ["Missouri", "missouri"], ["Montana", "montana"], ["Nebraska", "nebraska"], ["Nevada", "nevada"], ["New Hampshire", "new hampshire"], ["New Jersey", "new jersey"], ["New Mexico", "new mexico"], ["New York", "new york"], ["North Carolina", "north carolina"], ["North Dakota", "north dakota"], ["Ohio", "ohio"], ["Oklahoma", "oklahoma"], ["Oregon", "oregon"], ["Pennsylvania", "pennsylvania"], ["Rhode Island", "rhode island"], ["South Carolina", "south carolina"], ["South Dakota", "south dakota"], ["Tennessee", "tennessee"], ["Texas", "texas"], ["Utah", "utah"], ["Vermont", "vermont"], ["Virginia", "virginia"], ["Washington", "washington"], ["West Virginia", "west virginia"], ["Wisconsin", "wisconsin"], ["Wyoming", "wyoming"]]  end  def self.canada_provinces_with_caption          [["Alberta", "alberta"], ["British Columbia", "british columbia"], ["Manitoba", "manitoba"], ["New Brunswick", "new brunswick"], ["Newfoundland", "newfoundland"], ["Northwest Territories", "northwest territories"], ["Nova Scotia", "nova scotia"], ["Nunavut", "nunavut"], ["Ontario", "ontario"], ["Prince Edward Island", "prince edward island"], ["Quebec", "quebec"], ["Saskatchewan", "saskatchewan"], ["Yukon", "yukon"]]  end  

How do I select an option from this chosen selector in a Capybara integration test on the Ruby on Rails framework? I have tried the conventional selector method, and that hasn't work, as well as the Capybara method for filling out textboxes - and that hasn't worked for me either.

The HTML that the Chosen plugin creates from the ERB:

<select name="provinces[]" id="provinces" multiple="multiple" class="chosen-select chzn-select" data-placeholder="Filter Provinces/States" style="width: 100%; height: 100px; display: none;" data-original-title="" title=""><option value="420860745" data-original-title="" title="">Alabama</option>  <option value="121193182" data-original-title="" title="">Alaska</option>  <option value="614988510" data-original-title="" title="">Arizona</option>  <option value="1011954550" data-original-title="" title="">Arkansas</option>  <option value="51576297" data-original-title="" title="">California</option>  <option value="911438059" data-original-title="" title="">Colorado</option>  <option value="29252426" data-original-title="" title="">Connecticut</option>  <option value="742732841" data-original-title="" title="">Delaware</option>  <option value="335579331" data-original-title="" title="">District Of Columbia</option>  <option value="743108299" data-original-title="" title="">Florida</option>  <option value="302180340" data-original-title="" title="">Georgia</option>  <option value="245056076" data-original-title="" title="">Hawaii</option>  <option value="528006663" data-original-title="" title="">Idaho</option>  <option value="684024883" data-original-title="" title="">Illinois</option>  <option value="335439766" data-original-title="" title="">Indiana</option>  <option value="1042961784" data-original-title="" title="">Iowa</option>  <option value="252128415" data-original-title="" title="">Kansas</option>  <option value="908162754" data-original-title="" title="">Kentucky</option>  <option value="884793715" data-original-title="" title="">Louisiana</option>  <option value="633010136" data-original-title="" title="">Maine</option>  <option value="945883618" data-original-title="" title="">Maryland</option>  <option value="436583221" data-original-title="" title="">Massachusetts</option>  <option value="177885659" data-original-title="" title="">Michigan</option>  <option value="935527986" data-original-title="" title="">Minnesota</option>  <option value="312520863" data-original-title="" title="">Mississippi</option>  <option value="457050403" data-original-title="" title="">Missouri</option>  <option value="70125510" data-original-title="" title="">Montana</option>  <option value="376616596" data-original-title="" title="">Nebraska</option>  <option value="780899985" data-original-title="" title="">Nevada</option>  <option value="689473862" data-original-title="" title="">New Hampshire</option>  <option value="389522924" data-original-title="" title="">New Jersey</option>  <option value="380649796" data-original-title="" title="">New Mexico</option>  <option value="125610863" data-original-title="" title="">New York</option>  <option value="255810450" data-original-title="" title="">North Carolina</option>  <option value="428342329" data-original-title="" title="">North Dakota</option>  <option value="771165943" data-original-title="" title="">Ohio</option>  <option value="700707689" data-original-title="" title="">Oklahoma</option>  <option value="41766435" data-original-title="" title="">Oregon</option>  <option value="943799741" data-original-title="" title="">Pennsylvania</option>  <option value="764139748" data-original-title="" title="">Rhode Island</option>  <option value="720371240" data-original-title="" title="">South Carolina</option>  <option value="703335251" data-original-title="" title="">South Dakota</option>  <option value="562518602" data-original-title="" title="">Tennessee</option>  <option value="696317355" data-original-title="" title="">Texas</option>  <option value="299039922" data-original-title="" title="">Utah</option>  <option value="791562217" data-original-title="" title="">Vermont</option>  <option value="908498527" data-original-title="" title="">Virginia</option>  <option value="303977536" data-original-title="" title="">Washington</option>  <option value="512750023" data-original-title="" title="">West Virginia</option>  <option value="647404661" data-original-title="" title="">Wisconsin</option>  <option value="621732077" data-original-title="" title="">Wyoming</option>  <option value="100803856" data-original-title="" title="">Alberta</option>  <option value="950914246" data-original-title="" title="">British Columbia</option>  <option value="796505466" data-original-title="" title="">Manitoba</option>  <option value="536137098" data-original-title="" title="">New Brunswick</option>  <option value="4906295" data-original-title="" title="">Newfoundland</option>  <option value="65026714" data-original-title="" title="">Northwest Territories</option>  <option value="784270339" data-original-title="" title="">Nova Scotia</option>  <option value="768475533" data-original-title="" title="">Nunavut</option>  <option value="602098473" data-original-title="" title="">Ontario</option>  <option value="668705057" data-original-title="" title="">Prince Edward Island</option>  <option value="185902858" data-original-title="" title="">Quebec</option>  <option value="318605132" data-original-title="" title="">Saskatchewan</option>  <option value="585906940" data-original-title="" title="">Yukon</option></select>  

Followed by a second part:

<div class="chosen-container chosen-container-multi" style="width: 277px;" title="" id="provinces_chosen" data-original-title="">    <ul class="chosen-choices" data-original-title="" title="">      <li class="search-field" data-original-title="" title="">        <input type="text" value="Filter Provinces/States" class="default" autocomplete="off" style="width: 155px;" data-original-title="" title="">        </li>     </ul>   <div class="chosen-drop" data-original-title="" title="">     <ul class="chosen-results" data-original-title="" title="">       <li class="active-result" data-option-array-index="0">Alabama</li>       <li class="active-result" data-option-array-index="1">Alaska</li>       <li class="active-result" data-option-array-index="2">Arizona</li>       <li class="active-result" data-option-array-index="3">Arkansas</li>       <li class="active-result" data-option-array-index="4">California</li>       <li class="active-result" data-option-array-index="5">Colorado</li>       <li class="active-result" data-option-array-index="6">Connecticut</li>       <li class="active-result" data-option-array-index="7">Delaware</li>       <li class="active-result" data-option-array-index="8">District Of Columbia</li>       <li class="active-result" data-option-array-index="9">Florida</li>       <li class="active-result" data-option-array-index="10">Georgia</li>       <li class="active-result" data-option-array-index="11">Hawaii</li>       <li class="active-result" data-option-array-index="12">Idaho</li>       <li class="active-result" data-option-array-index="13">Illinois</li>       <li class="active-result" data-option-array-index="14">Indiana</li>       <li class="active-result" data-option-array-index="15">Iowa</li>       <li class="active-result" data-option-array-index="16">Kansas</li>       <li class="active-result" data-option-array-index="17">Kentucky</li>       <li class="active-result" data-option-array-index="18">Louisiana</li>       <li class="active-result" data-option-array-index="19">Maine</li>       <li class="active-result" data-option-array-index="20">Maryland</li>       <li class="active-result" data-option-array-index="21">Massachusetts</li>          <li class="active-result" data-option-array-index="22">Michigan</li>       <li class="active-result" data-option-array-index="23">Minnesota</li><li class="active-result" data-option-array-index="24">Mississippi</li>       <li class="active-result" data-option-array-index="25">Missouri</li>       <li class="active-result" data-option-array-index="26">Montana</li>       <li class="active-result" data-option-array-index="27">Nebraska</li>       <li class="active-result" data-option-array-index="28">Nevada</li>       <li class="active-result" data-option-array-index="29">New Hampshire</li>       <li class="active-result" data-option-array-index="30">New Jersey</li>       <li class="active-result" data-option-array-index="31">New Mexico</li>       <li class="active-result" data-option-array-index="32">New York</li>       <li class="active-result" data-option-array-index="33">North Carolina</li>       <li class="active-result" data-option-array-index="34">North Dakota</li>       <li class="active-result" data-option-array-index="35">Ohio</li>       <li class="active-result" data-option-array-index="36">Oklahoma</li>       <li class="active-result" data-option-array-index="37">Oregon</li>       <li class="active-result" data-option-array-index="38">Pennsylvania</li>       <li class="active-result" data-option-array-index="39">Rhode Island</li>       <li class="active-result" data-option-array-index="40">South Carolina</li>       <li class="active-result" data-option-array-index="41">South Dakota</li>       <li class="active-result" data-option-array-index="42">Tennessee</li>       <li class="active-result" data-option-array-index="43">Texas</li>       <li class="active-result" data-option-array-index="44">Utah</li>       <li class="active-result" data-option-array-index="45">Vermont</li>       <li class="active-result" data-option-array-index="46">Virginia</li>       <li class="active-result" data-option-array-index="47">Washington</li>       <li class="active-result" data-option-array-index="48">West Virginia</li><li class="active-result" data-option-array-index="49">Wisconsin</li>       <li class="active-result" data-option-array-index="50">Wyoming</li>       <li class="active-result" data-option-array-index="51">Alberta</li>       <li class="active-result" data-option-array-index="52">British Columbia</li>       <li class="active-result" data-option-array-index="53">Manitoba</li>       <li class="active-result" data-option-array-index="54">New Brunswick</li>       <li class="active-result" data-option-array-index="55">Newfoundland</li>       <li class="active-result" data-option-array-index="56">Northwest Territories</li>       <li class="active-result" data-option-array-index="57">Nova Scotia</li>       <li class="active-result" data-option-array-index="58">Nunavut</li>       <li class="active-result" data-option-array-index="59">Ontario</li>       <li class="active-result" data-option-array-index="60">Prince Edward Island</li>       <li class="active-result" data-option-array-index="61">Quebec</li>       <li class="active-result" data-option-array-index="62">Saskatchewan</li>       <li class="active-result" data-option-array-index="63">Yukon</li>     </ul>   </div>  

Hope the above info helps!

When trying to upgrade to Rails 5, getting "Bundler could not find compatible versions for gem "railties"" error

Posted: 26 Jul 2016 08:21 AM PDT

I'm trying to upgrade to Rails 5. I deleted my Gemfile.lock file, edited my Gemfile to look like below

source 'https://rubygems.org'      # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '5.0.0'  # Use sqlite3 as the database for Active Record  gem 'sqlite3'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks  gem 'turbolinks'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc    # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    # Use Unicorn as the app server  # gem 'unicorn'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development    gem 'addressable'  gem 'postgresql'  gem 'pundit'  gem 'omniauth-oauth2', '~> 1.3.1'  gem 'omniauth-google-oauth2'  gem 'omniauth-facebook'  gem 'omniauth-twitter'  gem 'omniauth-linkedin-oauth2'  gem 'jquery-rails'  gem 'jquery-ui-rails'  gem 'jquery-modal-rails'  gem 'will_paginate'  gem 'bootstrap-sass'  gem 'autoprefixer-rails'  gem 'whenever', :require => false  gem 'compass-rails'    group :development do    gem 'rails_layout'  end  

and ran "bundle install", only to get the below errors

$ bundle install  Your Gemfile lists the gem jquery-rails (>= 0) more than once.  You should probably keep only one of them.  While it's not a problem now, it could cause errors if you change the version of just one of them later.  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 "railties":    In Gemfile:      coffee-rails (~> 4.1.0) was resolved to 4.1.1, which depends on        railties (< 5.1.x, >= 4.0.0)        jquery-modal-rails was resolved to 0.0.1, which depends on        railties (< 5.0, >= 3.2.0)        jquery-rails was resolved to 4.1.1, which depends on        railties (>= 4.2.0)        rails (= 5.0.0) was resolved to 5.0.0, which depends on        railties (= 5.0.0)        sass-rails (~> 5.0) was resolved to 5.0.6, which depends on        railties (< 6, >= 4.0.0)        web-console (~> 2.0) was resolved to 2.3.0, which depends on        railties (>= 4.0)  

How do I properly edit my Gemfile so I can upgrade to Rails 5?

Rails, devise (4.2.0, 4.0.3) - Unlock token is invalid

Posted: 26 Jul 2016 07:52 AM PDT

Here is my unlock_instructions.html.erb code:

<p>Hello <%= @resource.email %>!</p>    <p>Your account has been locked due to an excessive number of unsuccessful sign in attempts.</p>    <p>Click the link below to unlock your account:</p>    <p><%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %></p>  

I am getting this link by email: http://my-corporate-care.herokuapp.com/users/unlock?unlock_token=YKBToxBnBYhfbtrC_5XH

Which is giving me an error like in the picture.

enter image description here

Don't know how to fix it since my code looks updated based on other posts I fetched?

For comparison, forgot password link works.

rails deployment failing - bitbucket and capistrano

Posted: 26 Jul 2016 08:14 AM PDT

I am trying to deploy rails application to ec2 server from bitbucket repository. When I run bundle exec cap staging deploy, I get the following error. Looking for help with how to solve this...I have followed the instructions on SSH key setup etc but that is not helping.

DEBUG [a02447fc]    Permission denied (publickey).  DEBUG [a02447fc]      DEBUG [a02447fc]    fatal: Could not read from remote repository.  DEBUG [a02447fc]      DEBUG [a02447fc]      DEBUG [a02447fc]    Please make sure you have the correct access rights  DEBUG [a02447fc]      DEBUG [a02447fc]    and the repository exists.  (Backtrace restricted to imported tasks)  cap aborted!  SSHKit::Runner::ExecuteError: Exception while executing as ubuntu@**IP address**: git exit status: 128  git stdout: Permission denied (publickey).  fatal: Could not read from remote repository.    Please make sure you have the correct access rights  and the repository exists.  git stderr: Nothing written    SSHKit::Command::Failed: git exit status: 128  git stdout: Permission denied (publickey).  fatal: Could not read from remote repository.    Please make sure you have the correct access rights  and the repository exists.  git stderr: Nothing written    Tasks: TOP => git:check  (See full trace by running task with --trace)  The deploy has failed with an error: Exception while executing as ubuntu@**IP addess**: git exit status: 128  git stdout: Permission denied (publickey).  fatal: Could not read from remote repository.    Please make sure you have the correct access rights  and the repository exists.  git stderr: Nothing written    ** DEPLOY FAILED  ** Refer to log/capistrano.log for details. Here are the last 20 lines:    bundler: failed to load command: cap (/home/admin1/mysite/vendor/bundle/ruby/2.2.0/bin/cap)  

omniauth-facebook error only when api version is over v2.2

Posted: 26 Jul 2016 07:52 AM PDT

I received email from facebook that my rails app is using v2.0 api and it will be deprecated. so I updated gem like this.

-    devise (3.5.6)  +    devise (4.2.0)    -    oauth2 (1.1.0)  +    oauth2 (1.2.0)    omniauth-facebook (3.0.0)  omniauth-oauth2 (1.3.1)  

I did not version up omniauth-oauth2 because of some unsolved issues.

after that, I change some deprecated view codes. and changed my config and restart server.

config.omniauth :facebook, APP_ID, APP_SECRET, scope: 'email', info_fields: 'email,name'  

It worked well but the facebook api version was still v2.0. so I googled and found this. https://github.com/mkdynamic/omniauth-facebook#api-version says that it's default version is v2.6 but I don't know why it still use v2.0. anyway, I changed config code like this.

config.omniauth :facebook, APP_ID, APP_SECRET, scope: 'email', info_fields: 'email,name', client_options: {  site: 'https://graph.facebook.com/v2.6',  authorize_url: "https://www.facebook.com/v2.6/dialog/oauth"  }  

but it did not work. log is like this.

Started GET "/users/auth/facebook/callback?code=verylogcode&state=stateblabla" for 127.0.0.1 at 2016-07-26 22:52:03 +0900  (facebook) Callback phase initiated.  (facebook) Authentication failure! invalid_credentials: OAuth2::Error, :   {"access_token":"very_long_token_value","token_type":"bearer","expires_in":5160039}  Processing by OmniauthCallbacksController#failure as HTML  

I downgraded the config version to v2.3 but it did not work. from v2.2, it works.

My Question is this.

  1. why the omniauth-facebook does not use v2.6 at default config setting?
  2. How can I solve this problem? I googled this kind of erros but in my case, the log does not show error messages precisely. (OAuth2::Error, : actually vacant)

Rails5 + ActionCable: WebSocket connection to 'ws://{hostname}/cable' failed: WebSocket is closed before the connection is established

Posted: 26 Jul 2016 07:00 AM PDT

I get WebSocket connection to 'ws://{hostname}/cable' failed: WebSocket is closed before the connection is established. in my chrome browser when connecting to my Rails 5 + ActionCable app. In my local development environment, it doesn't happen. It only happens in my staging and production environment.

Successful screenshot on development

Failed screenshot on staging

I use Amazon ElasticBeanstalk to deploy my app. After monitoring requests with chrome developer tool, I figured out that unlike development environment, WebSocket request in staging, production environment doesn't get response(pending) so ActionCable constantly tries to connect to the WebSocket endpoint (ws://{hostname}/cable).

The thing is, in my puma.log, it says something like this:

I, [2016-07-26T13:45:53.921154 #32369]  INFO -- : Registered connection (Z2lkOi8vYXNrLWNvLWRlL1VzZXIvMg)  I, [2016-07-26T13:46:05.775788 #32369]  INFO -- : Finished "/cable/" [WebSocket] for 121.166.105.106 at 2016-07-26 13:46:05 +0000  I, [2016-07-26T13:46:18.074895 #32369]  INFO -- : [917fd706-4f1a-4178-bd95-7a33c0c7b621] Started GET "/cable" for 121.166.105.106 at 2016-07-26 13:46:18 +0000  I, [2016-07-26T13:46:18.075764 #32369]  INFO -- : [917fd706-4f1a-4178-bd95-7a33c0c7b621] Started GET "/cable/" [WebSocket] for 121.166.105.106 at 2016-07-26 13:46:18 +0000  I, [2016-07-26T13:46:18.075817 #32369]  INFO -- : [917fd706-4f1a-4178-bd95-7a33c0c7b621] Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)  

that is, upgrade to WebSocket was successful but the rest is unknown. Do you have any clue on resolving this?

Passing a Rails Variable into a Controller Method

Posted: 26 Jul 2016 07:41 AM PDT

So, I've got a program that I've been working on for a while that is just a basic barcode scanning system.

My controller for a raw good is as below:

class RawsController < ApplicationController    def new          @raw = Raw.new    end            def create          @raw = Raw.new(params[raw_params])          if @raw.save              receive(@raw)              redirect_to new_raw_path          end           end      def receive(raw)          scanned = Raw.find_by(code: raw.code)          if scanned.quantity.nil?              flash[:danger] = "no match"          else              scanned.quantity += 1              if scanned.save                  respond_to do |format|                      format.html {}                      format.json{}                  end              end          end    end  private      def raw_params          params.require(:raw).permit(:code, :product, :quantity)      end    end  

Now, what I want to happen, is that when someone enters a barcode number into a form, it creates @raw as an instance of the Raw(for raw goods) class. Then in the receive function, it searches for a matching product in my inventory and then adds one unit to my raw goods inventory.

However once I get to the scanned.quantity += 1 line, I continually get an error that this method is undefined for nil class.

I added in the scanned.quantity.nil? line, and I do get that flash message, so I know the problem has to do with the quantity being nil. But, I'm not sure how to fix this.

Any help?

getting error in action cable rails 5

Posted: 26 Jul 2016 06:40 AM PDT

I write below code in game.coffe file

App.game = App.cable.subscriptions.create "GameChannel",    connected: ->     ...      disconnected: ->     ...    received: (data) ->      switch data.action        when "game_start"          $('#status').html("Player found")          App.gamePlay = new Game('#game-container', data.msg)          when "take_turn"          App.gamePlay.move data.move          App.gamePlay.getTurn()          when "new_game"          App.gamePlay.newGame()          when "opponent_withdraw"          $('#status').html("Opponent withdraw, You win!")          $('#new-match').removeClass('hidden');      take_turn: (move) ->      @perform 'take_turn', data: move      new_game: () ->      @perform 'new_game'  

when i run this code in browser it will show me erro like this

game.self-9aed049….js?body=1:42 Uncaught ReferenceError: Game is not defined  

in browser's console.

How can you match URLs using wildcards in Ruby/Rails? [on hold]

Posted: 26 Jul 2016 06:38 AM PDT

For example:

  • *.google.com === www.google.com/q?=query

  • * === anydomain.gov

  • *.facebook.* === www.facebook.com

localhost:3000 won't load while server is running, but it works after I restart the computer

Posted: 26 Jul 2016 06:43 AM PDT

Basically, when I type in "rails server" in the terminal, the server starts running, but my localhost:3000 page won't load. However, when I restart the computer and do the exact same thing, the page loads normally.

I've had this issue for a while now, but I haven't been able to figure out when exactly and why this happens. Any guidance would be much appreciated. Thank you.

Heroku website rails cant log in

Posted: 26 Jul 2016 07:21 AM PDT

Hi everyone I had a website working on localhost:3000 and after deploying it to heroku it wont log in either through email, facebook or google.

It says... We're sorry, but something went wrong.

If you are the application owner check the logs for more information.

This is the log, as far as I am aware.

2016-07-26T13:19:47.274514+00:00 app[web.1]:   [1m[36mSQL (1.6ms)[0m  [1mINSERT INTO "users" ("email", "encrypted_password", "fullname", "created_at", "updated_at", "confirmation_token", "confirmation_sent_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"[0m  [["email", "barryjamesreeves@gmail.com"], ["encrypted_password", "$2a$10$ueH7Epy29gga499pxMx2degMlD002aiT/ZO1nTObkRcJ8eAFmkLB2"], ["fullname", "Barry Reeves"], ["created_at", "2016-07-26 13:19:47.263106"], ["updated_at", "2016-07-26 13:19:47.263106"], ["confirmation_token", "A5xvp8bwrWeJMU56PbKd"], ["confirmation_sent_at", "2016-07-26 13:19:47.270010"]]  2016-07-26T13:19:47.278251+00:00 app[web.1]:   Rendered devise/mailer/confirmation_instructions.html.erb (1.5ms)  2016-07-26T13:19:47.290262+00:00 app[web.1]:     5: <p><%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %></p>  2016-07-26T13:19:47.290263+00:00 app[web.1]:   2016-07-26T13:19:47.290264+00:00 app[web.1]:   2016-07-26T13:19:42.157654+00:00 heroku[router]: at=info method=GET path="/sign_up" host=gentle-escarpment-62627.herokuapp.com request_id=b1a41126-4d0c-4bd0-9698-95cb04231e6a fwd="178.167.254.51" dyno=web.1 connect=1ms service=35ms status=200 bytes=4593  2016-07-26T13:21:03.812842+00:00 heroku[router]: at=info method=GET path="/auth/facebook" host=gentle-escarpment-62627.herokuapp.com request_id=49fcd867-4a2b-4bc1-8134-c2d351729251 fwd="178.167.254.51" dyno=web.1 connect=1ms service=7ms status=302 bytes=1426  

Any help appreciated thanks

Boolean on active admin field returns empty instead false (Rails 3.2/Active Admin)

Posted: 26 Jul 2016 07:13 AM PDT

I have a form called User with a boolean attribute called 'confirmed'. When I display all users or try to view each user, the confirmed value is always empty instead of false and I have searched alot and still I don't why this happen. Can anyone help me?

Note: 'confirmed' is shown as empty if it is false only.

Schema Migration:

create_table "users", :force => true do |t|     t.string   "name"     t.boolean  "confirmed",        :default => false     t.datetime "created_at",       :null => false     t.datetime "updated_at",       :null => false  end  

Index function and Form on active admin:

ActiveAdmin.register User do        index do          column :id          column :name          column :confirmed          actions      end        form do |f|          f.inputs "User Details" do              f.input :name              f.input :confirmed          end           f.actions      end    end  

"undefined method `address=' for" error using geocoder gem in rails

Posted: 26 Jul 2016 06:47 AM PDT

I am working on an application which can store vendor details along with lat/lon information. To make it geocodable I have used geocoder gem while using it on postgis. I have followed the complete documentation of geocoder. However while creating any new vendor I get the following error

NoMethodError in VendorsController#create    undefined method `address=' for #<Vendor:0x007faca1729a20> Did you   mean?addressline2=  

My rails vendors_controller.rb

class VendorsController < ApplicationController    before_action :set_vendor, only: [:show, :edit, :update, :destroy]        def index      @vendors = Vendor.all.limit(20)    end      def new      @vendor = Vendor.new    end      def create      @vendor = Vendor.new(vendor_params)      respond_to do |format|        if @vendor.save          format.html { redirect_to @vendor, notice: 'Vendor was         successfully created.' }        format.json { render :show, status: :created, location: @vendor }    else      format.html { render :new }      format.json { render json: @vendor.errors, status:      :unprocessable_entity }    end    end    end      def update      respond_to do |format|        if @vendor.update(vendor_params)          format.html { redirect_to @vendor, notice: 'Vendor was         successfully       updated.' }      format.json { render :show, status: :ok, location: @vendor }    else      format.html { render :edit }      format.json { render json: @vendor.errors, status:      :unprocessable_entity }    end    end    end       private  def set_vendor    @vendor = Vendor.find(params[:id])  end      def vendor_params    params.require(:vendor).permit(:name, :email, :phone_no, :addressline1,     :addressline2, :landmark,     :city, :state, :country, :pincode, :latitude, :longitude, :status)  end  end  

My vendor.rb

  class Vendor < ActiveRecord::Base    has_many :vendor_products    has_many :products, through: :vendor_products        geocoded_by :full_path    after_validation :geocode      reverse_geocoded_by :latitude, :longitude    after_validation :reverse_geocode      def full_path      [addressline1, addressline2, landmark, city, state, country,        pincode].compact.join(', ')    end   end  

My vendor schema

create_table "vendors", force: :cascade do |t|  t.string   "name"  t.string   "email"  t.string   "phone_no"  t.string   "addressline1"  t.string   "addressline2"  t.string   "landmark"  t.string   "city"  t.string   "state"  t.string   "country"  t.float    "latitude"  t.float    "longitude"  t.boolean  "status"  t.datetime "created_at",   null: false  t.datetime "updated_at",   null: false  t.string   "pincode"  end  

I do not have an address field used anywhere in the code at all. Yet it throws me this error whenever I try to create a new vendor both from the console as well as the form. I have tried restarting the server, it was a futile attempt. I am rails newbie and would really appreciate some help with an elaborate description.Let me know if you need more info

RSpec/Capybara: Strange behaviour doesn't find element with have_css, but it definitely is there

Posted: 26 Jul 2016 07:40 AM PDT

I have the following spec:

within dom_id_selector(@boilerplate_copy) do    within '.copied_attributes_differing_from_original' do      within 'form.title[action="http://www.textdiff.com/"]' do        expect(page).to have_css 'button', text: 'Title'        expect(page).to have_css 'input[name="string1"]'        expect(page).to have_css 'input[name="string2"]'      end    end  end  

Here is the HTML in question:

<div class="copied_attributes_differing_from_original">    <form action="http://www.textdiff.com/" class="title" method="post" target="_blank">      <input name="string1" type="hidden" value="Boilerplate Original test title">      <input name="string2" type="hidden" value="Boilerplate Copy test title">      <button type="submit">Title</button>    </form>      <form action="http://www.textdiff.com/" class="success_criterion_id" method="post" target="_blank">      <input name="string1" type="hidden">      <input name="string2" type="hidden" value="1">      <button type="submit">Success criterion</button>    </form>      // More of them...    <form action="http://www.textdiff.com/"...  </div>  

While the first have_css passes (the button is found), the second have_css fails:

Failure/Error: expect(page).to have_css 'input[name="string1"]'     expected to find css "input[name=\"string1\"]" but there were no matches. Also found "", which matched the selector but not all filters.  

But in my opinion this element definitely is there! I also don't understand the output Also found "", which matched the selector but not all filters., what does it mean?

Thank you.

How to pass parameter in data-url for edit method in rails

Posted: 26 Jul 2016 06:12 AM PDT

<%= f.select :current_user_insurance_insurance_company, companies_to_be_included, {include_blank:"None"}, class: "select-company", id:"insurance-company", data: { url: url_for([:new, @request, :user_insurance])} %>  

This is the data-url I have used for new method of insurance, so in order to edit insurance, how can I pass id for insurance in the data url. I tried to pass the id through the following method:

{ url: url_for([:edit, @request, :user_insurance])}  

and this is the error I got:

No route matches {:action=>"edit", :controller=>"user_insurances", :format=>nil, :id=>nil, :request_id=>

How can I use the rails console in a non-rails project?

Posted: 26 Jul 2016 06:13 AM PDT

My project is not a web server. I'm using ActiveRecord and ActiveSupport. I'd like to also have the rails console. How can I do this without generating an entire rails app (and/or, what's the most minimal way to do this?)

Paperclip saves images but doesn`t show it in views

Posted: 26 Jul 2016 06:02 AM PDT

I was using Paperclip for almost a month and it worked well. After some fixes in config and preparations for test it fell off and now it is saving images properly, but shows something like '%D0%97%D0%BD%D1%8F%D1%82%D0%BE%D0%BA_%D0%B5%D0%BA%D1%80%D0%B0%D0%BD%D1%83_%D0%B7_2016-06-28_11-35-01' instead of picture itself. Can you please tell ьу how to fix this or advise a guideline to mend such kind of stuff?

Linux cannot locate Gemfile or .bundle/directory even though it is/should be there

Posted: 26 Jul 2016 07:45 AM PDT

I am backing up gitlab from a server after this script. I have to type in:

sudo -u git -H bundle exec rake gitlab:backup:create RAILS_ENV=production  

The outcome of it is:

Could not locate `Gemfile` or `.bundle/` directory  

Am I doing something wrong here? If I search with the find command after Gemfile, Linux finds it, but if I use the locate command it doesn't. Does that mean there may be my error?

Active admin: reset password does not show an error after token is expired

Posted: 26 Jul 2016 05:34 AM PDT

When I generate the reset password link sent through active admin forgot passoword I am able to change the password and log in to the dashboard but when i try to use the same link again to change password it does nothing and redirects to same page. It shows no errors even when i enter empty passwords. I want it to show an error that the token is expired

the same log is generated every time I submit the form.

AdminUser Load (0.6ms) SELECT "admin_users".* FROM "admin_users" WHERE "admin_users"."reset_password_token" = '14ad4bc9d075cbb5ed8057c9518848e448e56beab6430ff1d3c7459771a79662' ORDER BY "admin_users"."id" ASC LIMIT 1 [["reset_password_token", "14ad4bc9d075cbb5ed8057c9518848e448e56beab6430ff1d3c7459771a79662"]] method=PUT path=/admin/password format=html controller=ActiveAdmin::Devise::PasswordsController action=update status=200 duration=606.45 view=570.88 db=0.64 time=2016-07-26 12:25:20 UTC category=web ip=127.0.0.1 params={"admin_user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "reset_password_token"=>"[FILTERED]"}, "commit"=>"Change my password"}

I have no idea why I gives 200 status.Any idea where I should start looking?

cant grab my id's from html with javascript to give them styles

Posted: 26 Jul 2016 06:09 AM PDT

I am doing color palettes and it needs to have a predefined palette and then choose the colors from it the thing is it must be mutable and for this I have come with this solution

            <div class='colorScope'>                  <div id="colorBackgroundDark<%=project.id%>">                      <div id="Dark1<%=project.id%>">                      </div>                      <div id="Dark2<%=project.id%>">                      </div>                  </div>                  <div id="colorBackgroundLight<%=project.id%>">                      <div id="Light1<%=project.id%>">                      </div>                      <div id="Light2<%=project.id%>">                      </div>                  </div>              </div>  

Project Id is given by rails, when a project with palettes is created (this is the html for the idea)

And here is the Js that should make the mutable palettes and is not working for some reason I am not able to figure out, I really hope you guys can please help me, please take in account again I am a rookie and be kind with me :x

function colorPalettes(id){      var myElement = document.getElementById('colorBackgroundDark'+id);      myElement.style.backgroundColor = "#D93600";      myElement.style.width = "50%";      myElement.style.height = "256px";        var myElement3 = document.getElementById('Dark1'+id);      myElement3.style.backgroundColor = "#D93600";      myElement3.style.width = "50%";      myElement3.style.height = "256px";        var myElement4 = document.getElementById('Dark2'+id);      myElement4.style.backgroundColor = "#D93600";      myElement4.style.width = "50%";      myElement4.style.height = "256px";        var myElement2 = document.getElementById('colorBackgroundLight'+id);      myElement2.style.backgroundColor = "#ffffff";      myElement2.style.width = "50%";      myElement2.style.height = "256px";        var myElement5 = document.getElementById('Light1'+id);      myElement5.style.backgroundColor = "#00474E";      myElement5.style.width = "50%";      myElement5.style.height = "256px";          var myElement6 = document.getElementById('Light2'+id);      myElement6.style.backgroundColor = "#6CEEFC";      myElement5.style.width = "50%";      myElement5.style.height = "256px";  }      $( document ).ready(function() {      var id = $('[type="range"]').attr('id')      colorPalettes(id);  });  

How to pass data before create a subscription in ActionCable - uniq connections

Posted: 26 Jul 2016 05:15 AM PDT

In my ActionCable channel I want to have every connection unique. How can I do it and pass params before create a subscription and find the params in the subscribed method?

Following the ActionCable documentation for all connections to same channel, the action starts here:

ActionCable.server.broadcast "web_notification_channel", id: id, title: title  

It launchs the JS file channels/web_notification.coffee

  App.link = App.cable.subscriptions.create { channel: "WebNotificationChannel"},        ..      # connected: ->      # disconnected: ->      # received: (data) ->        ..  

It creates the subscription here:

# app/channels/web_notification_channel.rb  class WebNotificationChannel < ApplicationCable::Channel    def subscribed      stream_from "web_notification_channel"    end  end  

Now I want to have for every connection a unique channel - following the documentation I would do something like this Start:

ActionCable.server.broadcast "web_notification_channel#{id}", id: id, title: title  

JS:

App.link = App.cable.subscriptions.create { channel: "WebNotificationChannel", id: ?}  

Subscription:

  def subscribed      stream_from "web_notification_channel#{params[:id]}"    end  

The problem is the second step - how can I get the data ID - so I could pass it the last step as a param?

I found this resource here but it's not a clear to me and I feel it's too complicated for my simple example.

How to change the head section of Index.html in a Ruby on Rails app?

Posted: 26 Jul 2016 07:40 AM PDT

In the head section of my Ruby on Rails app I am only able to see the following CSS and JS file when I view the source code in browser.

<link rel="stylesheet" media="all" href="/stylesheets/default.css" data-turbolinks-track="reload" />    <script src="/javascripts/default.js" data-turbolinks-track="reload">  

I have added bootstrap CSS and JS files to the app/assets/stylesheetsand app/assets/javascripts and have changed the application.css and application.js files. Still I am not able to see those files in source code.

Another thing I'd like to ask is how to give a header code to all the views in ROR app.

Rails, remove flash message generated via ajax

Posted: 26 Jul 2016 05:27 AM PDT

I have a flash message which is generated by an ajax response. In my controller I have:

def destroy    flash[:danger] = "Successfuly destroyed"    format.js  end   

which calls a destroy.js.erb file

$('#flash_messages').html("<%= escape_javascript (render partial: 'layouts/flash_messages') %>");  

that renders a partial which shows the flash messages. This partial looks like this:

#flash_messages    -flash.each do |key, value|      = content_tag(:div, value, class: "flash alert alert-#{key}")  

I would like to use jquery to remove the flash message after 2 seconds. What I tried was:

$(".alert").fadeTo(2000, 500).slideUp(500, function(){    $(".alert").alert('close');  });  

which, however, does not find the .alert class because it is generated after the page load. What is a workaround this problem :? Thank you!

How should I upload a large amount of data from iOS app to Rails server?

Posted: 26 Jul 2016 05:39 AM PDT

I want to upload from iOS app a large amount a data (it can be a files) to Rails server. I want to be able to handle the Internet connection lost and resume a transfer after Internet connection restored.

  1. What I should to use: web sockets, HTTP or something other?
  2. What are the useful tools/gems/libraries for iOS and Rails?

How to avoid connecting to the Elasticsearch client when running rails generator or other tasks?

Posted: 26 Jul 2016 04:54 AM PDT

I have a rails (4.2.6) app that includes the elasticsearch-model and elasticsearch-api gems. When I run rails g model ... in order to generate new boilerplate code, rails tries to connect to the Elasticsearch server. This is, of course, easily remedied but a little annoying for local development. I have a guard in config/initializers/elasticsearch.rb:

if defined?(Rails::Server)      Elasticsearch::Model.client = Elasticsearch::Client.new(          log: true,          host: 'myhost'      )  end  

which I had hoped would do the trick but it's not enough. My models look like the following (app/models/item.rb):

require 'elasticsearch/model'    class Item < ActiveRecord::Base      include Elasticsearch::Model      include Elasticsearch::Model::Callbacks  end  Item.import(force: true) # auto sync model with elasticsearch  

Would I need to include a guard there, too, for the import? Or is there any other easy way to circumvent Elasticsearch?

Rails app is deployed and on, but bundle not seeing rails

Posted: 26 Jul 2016 04:51 AM PDT

I use Rails 4 in my app and am deploying it using Ansible&Capistrano.

As an Ansible template I use playbook pretty similar to this one - https://github.com/JohnnyR1co/fashcards/blob/master/config/provision/playbook.yml

It installs ruby as well as anything else and After cap production deploy I am able to see app on (I can load some non-db related pages).

But when I try to run something like RAILS_ENV=production rails c from the current folder I get

The program 'rails' can be found in the following packages: * ruby-railties-3.2 * ruby-railties-4.0 Try: apt-get install <selected package>

Why is this so? App is up and running, so rails seem to be fine.

Also when I try to run bundle install I get an error that nokogiri is not installed, despite I installed it manually after deploy. What could be the reason here?

I believe problem could be in playbook.ymlfile. Ruby installation is done there and I am not sure how correct is it.

Example of something that is not thread-safe in Rails

Posted: 26 Jul 2016 05:06 AM PDT

I've seen threads like this on thread-safety in Rails and various web pages on the topic, and I'm sure everyone's great at reciting what it is and giving 'tips' on what isn't thread-safe ("class variables!"), but I can never seem to find a clear, simple, complete example of something that is actually not thread-safe in Rails, to the point where I wonder if anyone actually understands it at all.

I would be grateful if someone could prove me wrong and give:

  • a clear, simple, complete example of something that is not thread-safe in Rails. It should be clear where the code is (i.e., if it is in the controller, please show it as such) and nothing should be left to the reader's imagination (such as a method that doesn't exist). Also, there shouldn't be any superfluous code or logic.

  • exactly how it would be problematic in the context of two users connecting to the website at the same time, on two different threads.

  • how to rectify the problem.

The more significant and Rails-relevant the example, the better, so if you can give an example where one user might see another user's data (or similar), please do so.

How to upload multiple images in Rails 4 with Carrierwave - upload does not occur

Posted: 26 Jul 2016 04:30 AM PDT

I'm working on product catalog - each item (model: Item) has many images (model: ItemImage). For image upload I use Carrierwave gem. After submitting a form with Item attributes I see that all text/select fields works correctly except image ulpoad - I don't see any pictures on my "show" page and no new ItemImages in ActiveRecord.

I suppose that form_for generate correctly all queries with item attributes but item_controller don't save data from "item_images_attributes".

How can I fix that problem?

UPDATE:

I missed an error after form submittion - "Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: ImageMagick/GraphicsMagick is not installed""

#<ActiveModel::Errors:0x007f9982a5a690 @base=#<...>, @messages=  {:"item_images.image"=>["Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: ImageMagick/GraphicsMagick is not installed"]}>  

ALL WORKS without mini_magick gem - problem is in mini_magick installation.

I use Rails 4.2.6 + carrierwave 0.11.2 + mini_magick 4.5.1

Query with 2 images for upload:

Started PATCH "/items/15" for ::1 at 2016-07-26 12:35:27 +0300  Processing by ItemsController#update as HTML  Parameters: {"utf8"=>"✓", "authenticity_token"=>"fIcV7MQgCcca1E31bGC3R1ESPTLqfIgjowmIvygYyuodp1gHtkjbEBwYJ0NPMhAZk0mRxDH1xuvqmUOx9cL19g==", "item"=>{"name"=>"porsche 911 turbo", "category_ids"=>["1",""], "item_images_attributes"=>{"0"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f99846708c0 @tempfile=#<Tempfile:/var/folders/3m/522lw46j5rngq0gdp86r4_4c0000gn/T/RackMultipart20160726-58459-9jljsv.jpg>, @original_filename="0_21058_e8ca3262_L.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"item[item_images_attributes][0][image]\"; filename=\"0_21058_e8ca3262_L.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "1"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007f99846707a8 @tempfile=#<Tempfile:/var/folders/3m/522lw46j5rngq0gdp86r4_4c0000gn/T/RackMultipart20160726-58459-1eikktq.jpg>, @original_filename="0_57202_48ad8d07_XL.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"item[item_images_attributes][1][image]\"; filename=\"0_57202_48ad8d07_XL.jpg\"\r\nContent-Type: image/jpeg\r\n">}}}, "commit"=>"Сохранить изменения!", "id"=>"15"}  

Views

views/items/new.html.haml

%h1 Create new item    = form_for(@item, html: { multipart: true }) do |f|      = render partial: "layouts/item_form", locals: {f: f}      = f.submit 'Create item!'  %p      = link_to "All items", items_path  

views/items/edit.html.haml

%h1 Edit item:    = form_for(@item, html: { multipart: true }) do |f|      = render partial: "layouts/item_form", locals: {f: f}      = f.submit 'Save changes!'  %p      = link_to "link to item page", item_path(@item)  %p      = link_to "link to catalog", items_path(@item)  

views/layouts/_item_form.html.haml

= f.label :name, "Item name"  = f.text_field :name     = f.label :category_ids, 'Category'  = collection_check_boxes :item, :category_ids, Category.all, :id, :name    = f.fields_for :item_images do |item_image|     - if item_image.object.new_record?         = item_image.file_field :image     - else         = image_tag(item_image.object.image.url(:thumb))         = item_image.check_box :_destroy  

views/items/show.html.haml

%h1       = @item.name  %p      categories:      - @item.categories.each do |j|          = j.name  .input-gr      = form_for @position, remote: true do |f|          = f.hidden_field :quantity, value: 1          = f.hidden_field :item_id, value: @item.id          = f.submit "Add to cart", class: "btn btn-primary"   %p      = link_to "Edit item", edit_item_path(@item)  %p      = link_to "All items", items_path  

Models:

item.rb

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

item_image.rb

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

Controllers:

items_controller.rb

before_filter :find_item, only: [:show, :edit, :update, :destroy]    def new      @item=Item.new      3.times { @item.item_images.build }  end    def create      @item=Item.create(item_params)        if @item.errors.empty?          redirect_to item_path(@item)      else          render "new"      end  end    def show      @position=current_cart.positions.new      @images=@item.item_images  end    def edit      3.times { @item.item_images.build }  end    def update      @item.update_attributes(item_params)      if @item.errors.empty?          redirect_to item_path(@item)      else          render "edit"      end  end    def destroy      @item.destroy      redirect_to items_path  end    def index      @items=Item.all      @position_new=current_cart.positions.new    end      private      def find_item          @item=Item.find(params[:id])      end      def item_params          params.require(:item).permit(:name, :price, category_ids: [], item_images_attributes: [:id, :item_id, :image])      end  

ActiveRecord::Schema

ActiveRecord::Schema.define(version: 20160725185204) do      ...      create_table "item_images", force: :cascade do |t|      t.string   "image"      t.string   "item_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "items", force: :cascade do |t|      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.string   "name"      ...      end      ...    end  

Uploader

uploaders/image_uploader.rb

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

No comments:

Post a Comment