Monday, July 4, 2016

How to set upload image progress bar with Paperclip? | Fixed issues

How to set upload image progress bar with Paperclip? | Fixed issues


How to set upload image progress bar with Paperclip?

Posted: 04 Jul 2016 07:35 AM PDT

I tried searching for this but couldn't find a solution.. Is there any gem that can help? I only need simple progress bar for one file(image). I'm using standard Paperclip image setup.

Rails Javascript onsubmit validate() Uncaught ReferenceError: validate is not defined

Posted: 04 Jul 2016 07:22 AM PDT

I have a form of the following characteristics:

= nested_form_for reservation, html: { onsubmit: "return validate()"} do ...  

And the following file reservation.js:

jQuery(function() {    $('div.modal').on('loaded.bs.modal', function(e) {      ...some code...    });    $('div.modal').on('shown.bs.modal', function(e) {      ...some code...    });      function validate(){      var guests = 0;      $('.guests-input').each(function(i, e){        guests = guests + $(e).val();      });      if (guests < 1){        alert('Sum of percentage must be 100');        return false;      }      return true;    }  });  

But, when I click the submit button I get the error:

Uncaught ReferenceError: validate is not defined

I don't know where should I define it. I've searched other questions but I couldn't solve my problem with them. I'm not entirely sure either where should I look.

I'll edit with more information if needed.

How can I ensure that calling #changed? on an instance of an ActiveRecord model after a transaction rolls back returns true?

Posted: 04 Jul 2016 07:33 AM PDT

I found an issue in my code where a transaction block is rollback by explicitly raising an ActiveRecord::Rollback. In this case if an instance of a model saves successfully in the transaction before the rollback it ends up in a weird state.

Here is an example of a simple case that causes the issue:

record = SomeModel.last  record.attributes = { name: "A New Name"}    SomeModel.transaction do     record.save    raise ActiveRecord::Rollback  end  

If I called record.changed? after the transaction this will return false. However, if I call record.name after the transaction I would get a "A New Name". For some reason in this case the record has changes that were not persisted in the database, but ActiveRecord is not identifying these as changes anymore.

In my real-world application this is causing an issue in one area I use transactions. I have code where if a transaction fails I attempt to retry the transaction again with some changed parameters. If I reuse the instance that went through the first transaction without reloading it this results in the changes not being saved since they don't appear as changes.

Does anyone have any suggestions how to ensure that the instance has the changes and ActiveRecord still identifies these as changes?

Google maps autocomplete js is working on localhost but not on heroku

Posted: 04 Jul 2016 07:13 AM PDT

I'm a junior ruby on rails developer. I developed a web app that uses Google maps javascript API and I use the autocomplete function on a form input.

The autocomplete works fine on localhost but does not work anymore after deploying on heroku.

Here is my html.erb below. For your perfect information, the form is in the page footer. This form is partially hidden and the only visible part corresponds to a button used to upload a video file. Once this button has been clicked and the video file has been chosen, I display a modal containing the rest of the form. That's where the 'text_field_tag' (with the id = "user_input_autocomplete_address") is displayed and where the autocomplete should work.

<% if user_signed_in? %>    <div class="footer-check hidden-md hidden-lg">    <div class="container text-right">      <div class="row">        <div class="flexbox">          <div class="footer-home active">            <%= link_to root_path do %>              <i class="fa fa-home" aria-hidden="true"></i>            <% end %>          </div>          <div class="footer-search">          <!-- later put link_to reviews_path -->            <%= link_to search_path do %>              <i class="fa fa-search" aria-hidden="true"></i>            <% end %>          </div>          <div class="footer-button">          <%= simple_form_for(Review.new) do |f| %>            <div id="add_video_image_btn">              <label for="review_video", class="add_video_image"><%= image_tag "plus.png" %></label>              <%= f.input :video, label: false, input_html: { accept: ".mp4, .mov, .m4v, .wmv, .webm, .avi", class: 'hidden'} %>              <%= f.input :video_cache, as: :hidden, class: "add_video_image file required" %>            </div>          </div>          <div class="footer-likes">            <%= link_to dashboard_users_path do %>              <i class="fa fa-heart" aria-hidden="true"></i>            <% end %>          </div>            <div class="footer-user">            <%= link_to user_path(current_user) do %>              <i class="fa fa-user" aria-hidden="true"></i>            <% end %>          </div>        </div>      </div>    </div>  </div>    <!--Beginning Modal -->  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">  <div class="modal-dialog" role="document">    <div class="modal-content">      <div class="modal-body">        <div id="add_video_form_step2">          <%= f.error_notification %>            <fieldset class="form-group" style="margin-bottom:0;">              <div class="section">              Place            </div>            <div class="inner-wrap">              <div id="">                <%= text_field_tag :place, nil, class: 'form-control', id: 'user_input_autocomplete_address', placeholder: 'Start typing...', size: 80 %>              </div>            </div>              <div class="section">              Comment            </div>            <div class="inner-wrap">              <%= text_field_tag :comment, nil, class:'form-control', placeholder: 'Food is good but the place is a bit noisy', size: 80 %>            </div>              <div class="inner-wrap" style="padding:15px;">              <div class="emoji-toggle emoji-happy">                <input type="checkbox" id="toggle1" class="toggle" name="review[mood]" value="false">                <div class="emoji"></div>                <label for="toggle1" class="well"></label>              </div>            </div>              <div class="">              <%= f.button :submit, class: "btn btn-primary form-control", id: "click-trigger" %>            </div>              <%= hidden_field_tag :name, id: 'name' %>            <%= hidden_field_tag :street_number, id: 'street_number' %>            <%= hidden_field_tag :route, id: 'route' %>            <%= hidden_field_tag :locality, id: 'locality' %>            <%= hidden_field_tag :administrative_area_level_1, id: 'administrative_area_level_1' %>            <%= hidden_field_tag :postal_code, id: 'category_0' %>            <%= hidden_field_tag :country, id: 'country' %>            <%= hidden_field_tag :formatted_address, id: 'formatted_address' %>            <%= hidden_field_tag :phone_number, id: 'phone_number' %>            <%= hidden_field_tag :website, id: 'website' %>            <%= hidden_field_tag :gplace_id, id: 'gplace_id' %>            <%= hidden_field_tag :category_0, id: 'category_0' %>            <%= hidden_field_tag :category_1, id: 'category_1' %>            <%= hidden_field_tag :category_2, id: 'category_2' %>            <%= hidden_field_tag :category_3, id: 'category_3' %>            <%= hidden_field_tag :category_4, id: 'category_4' %>            <%= hidden_field_tag :category_5, id: 'category_5' %>            <%= hidden_field_tag :hours_open_day_0, id: 'hours_open_day_0' %>            <%= hidden_field_tag :hours_open_day_1, id: 'hours_open_day_1' %>            <%= hidden_field_tag :hours_open_day_2, id: 'hours_open_day_2' %>            <%= hidden_field_tag :hours_open_day_3, id: 'hours_open_day_3' %>            <%= hidden_field_tag :hours_open_day_4, id: 'hours_open_day_4' %>            <%= hidden_field_tag :hours_open_day_5, id: 'hours_open_day_5' %>            <%= hidden_field_tag :hours_open_day_6, id: 'hours_open_day_6' %>          </fieldset>        </div>      </div>      </div>    </div>  </div>          </div>        </div>      </div>    </div>  <% end %>  <% end %>    <!--End Modal -->    <!-- Start of js to display the modal -->  <!-- NB: the autocomplete module is in assets/javascript/autocomplete.js -->  <%= content_for :after_js do %>    <script>      $('#review_video').change(function(){        $('#myModal').modal('show');      });    </script>  <% end %>  <!-- End of js to display the modal -->

The footer (gathering the modal and the form) is called within a layouts/application.html.erb view, which is below. You'll see that I use Google API key in there (hidden in application.yml)

<!DOCTYPE html>  <html>    <head>      <title><%= meta_title %></title>      <%= csrf_meta_tags %>        <!-- Start Favicon -->        <%= favicon_link_tag '_/app/assets/images/favicon.ico' %>        <link rel="manifest" href="/manifest.json">      <meta name="msapplication-TileColor" content="#ffffff">      <meta name="msapplication-TileImage" content="<%= image_path 'ms-icon-144x144.png' %>">      <meta name="theme-color" content="#ffffff">      <!-- end Favicon -->        <meta name="description" content="<%= meta_description %>">        <!-- Facebook Open Graph data -->      <meta property="og:title" content="<%= meta_title %>" />      <meta property="og:type" content="website" />      <meta property="og:url" content="<%= request.original_url %>" />      <meta property="og:image" content="<%= meta_image %>" />      <meta property="og:description" content="<%= meta_description %>" />      <meta property="og:site_name" content="<%= meta_title %>" />        <!-- Twitter Card data -->      <meta name="twitter:card" content="summary_large_image">      <meta name="twitter:site" content="<%= DEFAULT_META["twitter_account"] %>">      <meta name="twitter:title" content="<%= meta_title %>">      <meta name="twitter:description" content="<%= meta_description %>">      <meta name="twitter:creator" content="<%= DEFAULT_META["twitter_account"] %>">      <meta name="twitter:image:src" content="<%= meta_image %>">        <!-- Google+ Schema.org markup -->      <meta itemprop="name" content="<%= meta_title %>">      <meta itemprop="description" content="<%= meta_description %>">      <meta itemprop="image" content="<%= meta_image %>">            <meta name="viewport" content="width=device-width, initial-scale=1">      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">      <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">      <%= stylesheet_link_tag    'application', media: 'all' %>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">        <!-- start Mixpanel -->      <script type="text/javascript">(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;b._i=[];b.init=function(a,e,d){function f(b,h){var a=h.split(".");2==a.length&&(b=b[a[0]],h=a[1]);b[h]=function(){b.push([h].concat(Array.prototype.slice.call(arguments,0)))}}var c=b;"undefined"!==typeof d?c=b[d]=[]:d="mixpanel";c.people=c.people||[];c.toString=function(b){var a="mixpanel";"mixpanel"!==d&&(a+="."+d);b||(a+=" (stub)");return a};c.people.toString=function(){return c.toString(1)+".people (stub)"};i="disable time_event track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config reset people.set people.set_once people.increment people.append people.union people.track_charge people.clear_charges people.delete_user".split(" ");        for(g=0;g<i.length;g++)f(c,i[g]);b._i.push([a,e,d])};b.__SV=1.2;a=e.createElement("script");a.type="text/javascript";a.async=!0;a.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?MIXPANEL_CUSTOM_LIB_URL:"file:"===e.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";f=e.getElementsByTagName("script")[0];f.parentNode.insertBefore(a,f)}})(document,window.mixpanel||[]);        mixpanel.init("ENV['MIXPANEL_TOKEN']");      </script>      <!-- end Mixpanel -->      </head>    <body>      <%= render 'shared/flashes' %>      <%= yield %>      <%= render 'shared/footer' %>      <%= javascript_include_tag "http://maps.google.com/maps/api/js?libraries=places&key=#{ENV['GMAP_BROWSER_KEY']}" %>      <%= javascript_include_tag "http://cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js" %>      <%= javascript_include_tag 'application' %>      <%= yield :after_js %>    </body>  </html>

Last, the javascript code allowing the autocomplete on the input (having "user_input_autocomplete_address" as id) is in assets/javascript/autocomplete.js and is the following :

function initializeAutocomplete(id) {    var element = document.getElementById(id);    console.log('coucou');    if (element) {      var autocomplete = new google.maps.places.Autocomplete(element, { types: ['geocode', 'establishment'] });      google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChanged);    }  }    function onPlaceChanged() {    var place = this.getPlace();      console.log(place);  // Uncomment this line to view the full object returned by Google API.      for (var i in place.address_components) {      var component = place.address_components[i];      // console.log(component.types);      for (var j in component.types) {  // Some types are ["country", "political"]        var type_element = document.getElementById(component.types[j]); // Returns the div with their differents ids or null if the id doesnt exist        // console.log(document.getElementById(component.types[j]));        if (type_element) {          type_element.value = component.long_name;        }      }    }      var formatted_address = document.getElementById('formatted_address');    // console.log(international_phone_number);    if (formatted_address) {      formatted_address.value = place.formatted_address;    }      for (var i in place.types) {      // console.log(place.types);      // console.log(i);      // console.log(place.types[i]);      var type_content = document.getElementById('category_' + i); // Returns the div with their differents ids or null if the id doesnt exist      // console.log(document.getElementById(component.types[j]));      if (type_content) {        console.log(place.types[i]);        type_content.value = place.types[i];      }    }      var international_phone_number = document.getElementById('phone_number');    // console.log(international_phone_number);    if (international_phone_number) {      international_phone_number.value = place.international_phone_number;    }      var name = document.getElementById('name');    if (name) {      name.value = place.name;    }      var gplace_id = document.getElementById('gplace_id');    if (gplace_id) {      gplace_id.value = place.place_id;    }      var website = document.getElementById('website');    if (website) {      website.value = place.website;    }      for (var i in place.opening_hours.weekday_text) {      var hours_open_in_db = place.opening_hours.weekday_text[i];      var hours_open_in_form = document.getElementById('hours_open_day_' + i);      if (hours_open_in_form) {        hours_open_in_form.value = hours_open_in_db;      }    }  }    google.maps.event.addDomListener(window, 'load', function() {    initializeAutocomplete('user_input_autocomplete_address');  });

In order to deploy all this on heroku, I already did the following :

  1. "heroku run db:migrate" in the terminal (because I had some pending migrations);
  2. "figaro heroku:set -e production" in the terminal, in order to push all my API keys to heroku (I also checked that these keys are indeed in heroku's config vars).
  3. in Google's developer console, within my project and within Google map javascript API, I ensured that my browser key is allowed for both my locahost and my domain name. In order to be very precise, I am using the same key for my locahost and my domain name. Until now, the only thing I have not managed to do yet, in Google's console, is to prove that I own my domain name.
  4. I checked I have not reached any of my API quotas yet.
  5. Within my autocomplete.js file, I used some console.log in order to find out, in my browser's inspector, what parts of the code are working. It seems that everything works except the console.logs that are in the 'OnPlaceChange' callback, since Gmap's autocomplete suggestions are not shown... ;
  6. I know that not seeing the autocomplete suggestions is not a problem of z-index associated to the .pac-container css element, since I already had to fix this and since Gmaps suggestions cannot be reached thanks to my keyboard arrows.
  7. I read this post about geocomplete (geocomplete for rails 4 not working in Heroku) and tried to precompile my assets. That did not lead to any change.
  8. In my browser inspector (in the 'network' section), when I write something in my form input, every new letter pressed on the keyboard triggers a new request. These requests names are 'AutocompletionService.GetPredictions.....'. In the "headers" section, I can see they are https requests to googleapis, with get methods and 200 status code. In the "response" section, I can see there seems to be a error with my API keys since the message is :

/**/_xdc_._ty4oqn && _xdc_._ty4oqn( [3,null,null,"This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console: https://console.developers.google.com/apis/library?project=_ Please ensure this API is activated in the Google Developers Console: https://console.developers.google.com/apis/api/places_backend?project=_ For more information on authentication and Google Maps Javascript API services please see: https://developers.google.com/maps/documentation/javascript/get-api-key"] )
I followed the link in the error message, leading me to Google's console, and I get back to my project and API keys, which are settled both server-side and browser-side. Once again, the only thing i did not managed to do in Google's console was to prove I own my domain name.

Is this last point the origin of the issue (and in this case I guess I need some help from my hosting services) or do you guys see another mistake?

Rails: datetime_field does not display control buttons

Posted: 04 Jul 2016 07:30 AM PDT

I have a form, where I use date_field helper and it works well, the control buttons are shown, but when I change it with a datetime_field the field is displayed but control buttons are no displayed.

My date_field which works fine:

=f.date_field :publishing_date, placeholder: "yyyy-mm-dd", class: "form-control"  

the datetime_field which does not shown controls:

=f.datetime_field :publishing_date, class: "form-control"  

how to delete record from a join table in rails

Posted: 04 Jul 2016 07:30 AM PDT

I have a join table having two record list_id and car_id. I want to delete a record where list_id = 5 and car_id = 7 for example. Here is my code in the controller section:

def deletejoin    @car = Car.find(params[:id])    end    def destroyjoin      #  car = Car.find(params[:id])      #  list = List.find(params[:list_id])      # car = Car.find(21.to_i)      # list = List.find(8)      #  puts car      #  puts list       car = Car.find(params[:id])       @list = car.lists.find(params[:list_id])       cars_lists.where(car_id: 25).destroy_all      #  @list.cars.where(:id => params[:id]).destroy_all      #  @list = @car.cars_lists.find(params[:list_id])      # @list.destroy      # car = Car.find(params[:id]).destroy      flash[:notice] = "Car #{car.name} destoryed successfully"      redirect_to(:action => 'index', :list_id => @list.id)    end  

convert to string to array in ruby or javascript to be in used in an SQL query

Posted: 04 Jul 2016 07:11 AM PDT

I am trying to convert a string to an array either in ruby on rails or in javascript or even jquery.

In my code, i get the values of the strings from a select option. So on option selected, i capture this value which returns the string

var lenders = $(this).val();  

This is the string it returns. Just a line of id numbers separated by commas "15,16,17" and i want to convert it to an array like this [15, 16, 17] either in ruby or in javascript.

How do i achieve this?

I have tried doing

"15,16,17".split(',')  

i have also tried doing "15,16,17".to_a

but all to no avail

How can i get the value of primary_value in activerecord has_many definition?

Posted: 04 Jul 2016 06:41 AM PDT

# == Schema Information  #  # Table name: books  # id           :integer   # owner_id     :integer    # Table name: users  # id           :integer    # Table name: shared_books_records  # user_id      :integer  # book_id      :integer  

I want to get all books user have.

def all_ books    join_sql = <<-SQL.squish!      LEFT OUTER JOIN shared_books_records        ON shared_books_records.user_id = books.assignee_id    SQL      Book.joins(join_sql)        .where("books.owner_id = :user_id OR shared_books_records.user_id = user_id", user_id: id)  end  

I think it's not very good, activerecord association is better. So I want to redefine it.

has_many :all_books, -> {  }, class_name: Book, foreign_key: :owner_id  

But I don't know how to get the value of primary_key in the scope.

How do I send emails using Sendgrids API to send emails with rails 4? I can seem to put all the pieces together

Posted: 04 Jul 2016 05:31 AM PDT

I want to send emails with sendgrids API from a google cloud platform instance. They have a short tutorial on how to do this but it has the email message, who its from, who to send to, and other info all in app.rb which isnt the normal way messages are sent in rails apps.

I looked at the sendgrid ruby docs and they also dont have very good information. All the info in in one place and they dont state what files to put them in or even mention any smtp settings to use.

Here is what I have so far

development.rb

config.action_mailer.delivery_method = :smtp  # SMTP settings  config.action_mailer.smtp_settings = {   :address              => "smtp.sendgrid.net",   :port                 => 465,   :domain               => "mydomain.com",   :user_name            => ENV['sendgrid_username'],   :password             => ENV['sendgrid_password'],   :authentication       => :plain,   :ssl                  => true,   :enable_starttls_auto => true  }  

gemfile

gem "sendgrid-ruby"  

The email views are in app/views, the mailer methods are in app/mailer the same as normal rails 4 apps have it setup.

So I guess here are my main questions:

  1. Where do I call the environment variables holding the sendgrid api key?
  2. Where do I tell Action Mailer to use sendgrid or SendGrid::Mail as I've seen in a couple of places?
  3. Do I even need the sendgrid gem?
  4. Are the smtp settings correct for sending over SSL with sendgrid?

I'm new to sending emails like this in a rails app and would really appreciate the help.

rails/middleman dependencies requires different versions of a gem

Posted: 04 Jul 2016 07:07 AM PDT

I was trying to add the middleman-cloudfront gem to my middleman project, but got the following error. Most of the gems needs >= 4.0 version of the the middleman-core gem, but the middleman-cloudfront requires ~> 3.0 version.

How can I solve this issue?

Bundler could not find compatible versions for gem "middleman-core":    In Gemfile:  middleman (>= 4.0.0) was resolved to 4.0.0, which depends on    middleman-core (= 4.0.0)    middleman-cloudfront (~> 0.2.1) was resolved to 0.2.1, which depends on    middleman-core (~> 3.0)    middleman-google-analytics (>= 2.1.1, ~> 2.1) was resolved to 2.1.1, which depends on    middleman-core (>= 3.4)    middleman-s3_sync (>= 4.0.3, ~> 4.0) was resolved to 4.0.3, which depends on    middleman-core (>= 4.0.0)    middleman-s3_sync (>= 4.0.3, ~> 4.0) was resolved to 4.0.3, which depends on    middleman-core (>= 4.0.0)    middleman-sprockets (~> 4.0) was resolved to 4.0.0, which depends on    middleman-core (~> 4.0)  

Haml: syntax error, unexpected keyword_ensure, expecting end-of-input

Posted: 04 Jul 2016 05:32 AM PDT

In my project, I am using haml to code the views, and in this partial, server shows syntax error, unexpected keyword_ensure, expecting end-of-input error:

.col-xs-12#new_posts_form     %h2= "New posts"    = form_tag admin_articles_posts_path      - @posts.each_with_index do |post,i|        = fields_for "posts[#{i}]", post do |f|           .col-xs-12            %label Content            = f.text_area :content, placeholder: "Content", class: "form-control"          .col-xs-12            %label Publishing date            =f.date_field :start_date, placeholder: "yyyy-mm-dd", class: "form-control"          .col-xs-12            = f.submit "Next", class: "btn btn-default"  

the error points line 13, the last one.

Rails scope with method value comparison

Posted: 04 Jul 2016 05:53 AM PDT

So i'm fairly new to rails and ActiveRecord and I have a need for a scope to filter between Client entities. Basically the scope should return all Client records where the client's current state is equal to a certain state object.

This is calculated by getting a client's last state_change and then pulling that state_change's from_state which is a State object.

I have defined a method to return the current_state however in rails console when I test it with Client.current_state(Client.last) I get this error:

NameError: undefined local variable or method 'state_changes for #<Class:0x0000000685eb88> but when running Client.last.state_changes in console it works fine.

My client.rb

class Client < ActiveRecord::Base    has_and_belongs_to_many               :users    belongs_to                            :industry    belongs_to                            :account    has_many                              :contacts    has_many                              :state_changes    belongs_to                            :head,          class_name: "Client"    has_many                              :branches,      class_name: "Client", foreign_key: "head_id"    has_many                              :meetings,      through: :contacts    has_many                              :sales,         through: :meetings      scope :prospects, -> (client) { where(Client.current_state(client): State.PROSPECT_STATE) }      def self.has_at_least_one_sale? (client)      return client.sales.empty?    end      def self.has_account_number? (client)      return client.account_number.present?    end      def self.current_state (client)      state_changes.last.to_state    end  end  

state_change.rb

class StateChange < ActiveRecord::Base    belongs_to :client    belongs_to :from_state,   class_name: "State", foreign_key: :to_state_id    belongs_to :to_state,     class_name: "State", foreign_key: :from_state_id  end  

state.rb

class State < ActiveRecord::Base    has_many :from_states,    class_name: "StateChange", foreign_key: :to_state_id    has_many :to_states,      class_name: "StateChange", foreign_key: :from_state_id      def self.PROSPECT_STATE      return State.find_by name: 'Prospect'    end      def self.CLIENT_STATE      return State.find_by name: 'Client'    end      def self.SUSPECT_STATE      return State.find_by name: 'Suspect'    end  end  

I also get syntax errors regarding the scope I defined in client.rb. I have followed the ActiveRecord guide but they don't explain how to have chained methods in the actualy scope query.

nil is getting saved for an image in carrierwave

Posted: 04 Jul 2016 05:16 AM PDT

A product can have multiple images. But each image should be uploaded one at a time.

Here is the schema for the product

create_table "products", force: :cascade do |t|      t.json     "images"    end  

Here is the carrierwave mounting

class Product < ActiveRecord::Base      mount_uploader  :images, ProductUploader    end  

Here is the carrierwave generator

class ProductUploader < CarrierWave::Uploader::Base      # Include RMagick or MiniMagick support:    # include CarrierWave::RMagick    # include CarrierWave::MiniMagick      # Choose what kind of storage to use for this uploader:    storage :file    # storage :fog      # Override the directory where uploaded files will be stored.    # This is a sensible default for uploaders that are meant to be mounted:    def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end      # Provide a default URL as a default if there hasn't been a file uploaded:    # def default_url    #   # For Rails 3.1+ asset pipeline compatibility:    #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))    #    #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')    # end      # Process files as they are uploaded:    # process scale: [200, 300]    #    # def scale(width, height)    #   # do something    # end      # Create different versions of your uploaded files:    # version :thumb do    #   process resize_to_fit: [50, 50]    # end      # Add a white list of extensions which are allowed to be uploaded.    # For images you might use something like this:    # def extension_whitelist    #   %w(jpg jpeg gif png)    # end      # Override the filename of the uploaded files:    # Avoid using model.id or version_name here, see uploader/store.rb for details.    # def filename    #   "something.jpg" if original_filename    # end    end  

Here is the view

<%= simple_form_for @product, method: :post, url: save_image_path do |f| %>            <%= f.file_field :avatar_1 %>            <%= f.submit :submit %>        <% end %>  

Here is the controller

class UploadController < ApplicationController    def show      @product = Product.find(1)    end      def create      byebug      @product = Product.find(1)      @product.images = params[:product][:avatar_1]      @product.save      end      end  

enter image description here

But the nil is getting updated in the images of product, instead of image. Can someone please help me with this.

_cart.html.erb partial not showing in navbar

Posted: 04 Jul 2016 06:34 AM PDT

Im working on a E store in rails. I've a _navbar partial in the partial I've <%= render 'cart' %>. The thing is that this cartpartial doesn't show up in the navbar and I really can't figure out why? I don't see anything in the code that should make it disappear.

this is my _navbar.html.erb partial

  <div class="navbar navbar-default navbar-fixed-top">        <div class="container-fluid">               <!-- Header -->          <div class="navbar-header">              <button type="button" class="navbar-toggle"                       data-toggle="collapse"                       data-target=".navbar-collapse">                  <span class="icon-bar"></span>                  <span class="icon-bar"></span>                  <span class="icon-bar"></span>              </button>                <%= link_to "Hlín Reykdal", root_path, class: 'navbar-brand' %>            </div>          <!-- Navbar Links -->          <div class="collapse navbar-collapse">              <ul class="nav navbar-nav">                  <li class="dropdown full-width">                      <a href="#" class="dropdown-toggle"                       data-toggle="dropdown">                          Shop                      </a>                          <ul class="dropdown-menu" role="menu">                              <% @categories.each do |category| %>                              <li><%= link_to category.name, category %></li>                          <% end %>                            </ul>                  </li>                               <li class="dropdown full-width">                      <a href="#" class="dropdown-toggle"                       data-toggle="dropdown">                          Designers                      </a>                          <ul class="dropdown-menu" role="menu">                             <% @designers.each do |designer| %>                              <li><%= link_to designer.designer_name, designer %></li>                          <% end %>                                  </ul>                  </li>                               <li class="dropdown full-width">                      <a href="#" class="dropdown-toggle"                       data-toggle="dropdown">                          Info                      </a>                      <ul class="dropdown-menu" role="menu">                          <li><%= link_to "About", pages_about_path %></li>                            <li><%= link_to "Stockists", stockists_path %></li>                             <li class="divider"></li>                          <li><a href="#">Location</a></li>                          <li class="divider"></li>                          <li><%= link_to "Help", pages_help_path %></li>                       </ul>                  </li>                        <% if current_user && current_user.admin? %>               <li class="dropdown full-width">                      <a href="#" class="dropdown-toggle"                       data-toggle="dropdown">                          Admin                      </a>                        <ul class="dropdown-menu" role="menu">                          <li><%= link_to "Products", products_path %></li>                          <li><%= link_to "Categories", categories_path %></li>                          <li><%= link_to "Designers", designers_path %></li>                          <li><%= link_to "Stockists", stockists_path %></li>                        </ul>                    </li>                       <% else %>                 <% end %>                    <% if user_signed_in? %>                    <li class="dropdown full-width">                     <p class="navbar-link"> Logged in as <%= current_user.name %>.</p>                     </li>                     <li>                      <%= link_to "Logout", destroy_user_session_path, method: :delete %> </li>                      <% else %>                  <li class="dropdown full-width">                        <%= link_to "Login", new_user_session_path, class: "navbar-link" %>                  <% end %>                              </li>                         <%= render 'cart' %>                        <%= render 'search' %>                 </ul>          </div>         </div>       </div>        <script src="js/bootstrap.min.js" type="text/javascript"></script>  <script>    /**   * Listen to scroll to change header opacity class   */  function checkScroll(){      var startY = $('.navbar').height() * 2; //The point where the navbar changes in px        if($(window).scrollTop() > startY){          $('.navbar').addClass("scrolled");      }else{          $('.navbar').removeClass("scrolled");      }  }    if($('.navbar').length > 0){      $(window).on("scroll load resize", function(){          checkScroll();      });  }  </script>  <script>      $('.dropdown').hover(          function() {              $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn();          },           function() {              $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut();          }      );        $('.dropdown-menu').hover(          function() {              $(this).stop(true, true);          },          function() {              $(this).stop(true, true).delay(200).fadeOut();          }      );  </script>  

this is the _cart.html.erb

<% if @cart %>     <li class="dropdown full-width ">       <a href="#" class="dropdown-toggle"                       data-toggle="dropdown">               <% if @cart.empty? %>                          Cart 0                   <% else %>                     <%= link_to "Cart #{pluralize @cart.count, "item"}", cart_path %>               <% end %>       </a>     </li>    <% end %>  

somehow the _cart.html.erb is only visible in the products/search.html.erbI don´t have a clue why it is only showing when I´m on that page.

this is the code for products/search.html.erb

<div class="container">  <div class="row product_top">  <table class="table table-hover">    <thead>      <tr>        <th>Name</th>        <th>Description</th>        <th>Designer</th>        <th>Price</th>        <th>Stock</th>        <th>Image</th>        </tr>    </thead>    <tbody>    <% @products.each do |product| %>          <tr>          <td><%= link_to product.name, product %></td>          <td><%= product.description %></td>          <td><%= product.designer.designer_name %></td>            <td><%= number_to_currency product.price %></td>          <td><%= product.stock_quantity %></td>            <td><%= image_tag product.image.thumb %></td>        <% end %>    </tr>  </tbody>  </table>  </div>  </div>  

EDITED

_cart.html.erb and _navbar.html.erb are both stored in views/application

here is carts_controller.rb

class CartsController < ApplicationController      before_filter :initialize_cart        def add          @cart.add_item params[:id]          session["cart"] = @cart.serialize          product = Product.find params[:id]          redirect_to :back, notice: "Added #{product.name} to cart."      end        def show        end        def checkout          @order_form = OrderForm.new user: User.new          @client_token = Braintree::ClientToken.generate      end  end  

here is application_controller.rb

class ApplicationController < ActionController::Base    # Prevent CSRF attacks by raising an exception.    # For APIs, you may want to use :null_session instead.    protect_from_forgery with: :exception    before_action :find_categories    before_action :find_designers        def initialize_cart      @cart = Cart.build_from_hash session    end      def find_categories      @categories = Category.all    end      def find_designers      @designers = Designer.all    end      def authenticate_admin!      authenticate_user!        unless current_user.admin?        redirect_to root_path, alert: "You are not allowed to perform that operation."      end    end  end  

products_controller.rb

class ProductsController < ApplicationController    before_action :set_product, only: [:show, :edit, :update, :destroy]    before_filter :initialize_cart    before_action :authenticate_admin!, only: [ :new, :edit, :update, :create, :destroy ]    # GET /products    # GET /products.json    def index      @products = Product.all    end      def search        @products = Product.search(params[:query]).order("created_at DESC")      @categories = Category.joins(:products).where(:products => {:id => @products.map{|x| x.id }}).distinct      end      # GET /products/1    # GET /products/1.json    def show      end      # GET /products/new    def new      @product = Product.new    end      # GET /products/1/edit    def edit      end      # POST /products    # POST /products.json    def create      @product = Product.new(product_params)        respond_to do |format|        if @product.save          format.html { redirect_to @product, notice: 'Product was successfully created.' }          format.json { render :show, status: :created, location: @product }        else          format.html { render :new }          format.json { render json: @product.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /products/1    # PATCH/PUT /products/1.json    def update      respond_to do |format|        if @product.update(product_params)          format.html { redirect_to @product, notice: 'Product was successfully updated.' }          format.json { render :show, status: :ok, location: @product }        else          format.html { render :edit }          format.json { render json: @product.errors, status: :unprocessable_entity }        end      end    end      # DELETE /products/1    # DELETE /products/1.json    def destroy      @product.destroy      respond_to do |format|        format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_product        @product = Product.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def product_params        params.require(:product).permit(:name, :description, :price, :image, :category_id, :stock_quantity, :designer_id, :query)      end  end  

I've spent all morning trying to figure this out with no luck. Can anyone here take a look at this and inform me?

thanks in advance D

Memory Model in Ruby

Posted: 04 Jul 2016 05:34 AM PDT

How memory is managed in ruby. For Ex: if we take the C program during execution, the following is the memory model. Similar to this how memory is handled in ruby.

  C:                         __________________                          |                |                          |      stack     |                          |                |                          ------------------                          |                |                          |   <Un Allocated|                          |       space>   |                          ------------------                          |                |                          |                |                          |       Heap     |                          |                |                          |                |                          __________________                          |                |                          |       data     |                          __________________                          |       text     |                          __________________    Ruby:                   ?  

Getting the ID of a resource in a nested URL Rails 4

Posted: 04 Jul 2016 05:42 AM PDT

What I'm looking to do is set the "album_id" attribute of my Song instance equal to the ID of the album currently being viewed.

For example:

http://localhost:3000/artist_profiles/1/albums/2

In the above URL, I would like to set the "album_id" of the song I am creating equal to 2.

My songs_controller:

class Albums::SongsController < ApplicationController      before_filter :set_user_friendships      def new    end      def create      # Make an object in your bucket for your song      obj = S3_BUCKET.objects[params[:file].original_filename]        # Upload the file      obj.write(        file: params[:file],        acl: :public_read      )        # Create an object for the song      @song = Song.new(          url: obj.public_url,          name: obj.key          )        @song.album_id = Album.find(params[:id])        # Save the upload      if @song.save        redirect_to artist_profile_albums_path(current_user.id), success: 'File successfully uploaded'      else        flash.now[:notice] = 'There was an error'        render :new      end    end      def index      @user_friendships = current_user.user_friendships.all      @songs = Song.all    end      def song_params      params.require(:song).permit(:id, :url, :name, :song_title, :album_id)    end      def set_user_friendships      @user_friendships = current_user.user_friendships.all #this is here because of partial UGHHH    end    end  

More specifically, the following line:

@song.album_id = Album.find(params[:id])  

However, when I try this code I get the following error:

Couldn't find Album with 'id'=  

If I try:

@song.album_id = Album.find(2).id  

or:

@song.album_id = 2  

I get 0 errors.

The route I am looking at after running the rake routes command is:

/artist_profiles/:artist_profile_id/albums/:id(.:format)   

How would I go about getting the ID of the proper album?

Any help is appreciated!

UPDATE:

My log when attempting to upload the song:

Started POST "/songs" for ::1 at 2016-07-04 07:34:32 -0400  Processing by Albums::SongsController#create as HTML    Parameters: {"utf8"=>"✓", "authenticity_token"=>"/pZp493WqiDgkJC72ueK5Wr4eVqdVvWzY43c/ru/OpSt3J9gECwC7nIhszLgyef218sRWsAr9xSZOnH751MUoA==", "file"=>#<ActionDispatch::Http::UploadedFile:0x007ff871c261b0 @tempfile=#<Tempfile:/var/folders/xb/38dybzwn51g3fg4vb7kdgg5m0000gn/T/RackMultipart20160704-11159-5aarh7.mp3>, @original_filename="03 Exit Wounds (Original Mix).mp3", @content_type="audio/mp3", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"03 Exit Wounds (Original Mix).mp3\"\r\nContent-Type: audio/mp3\r\n">, "commit"=>"Upload song"}    User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]  [AWS S3 200 16.701785 0 retries] put_object(:acl=>:public_read,:bucket_name=>"atmosphere-development",:content_length=>13561000,:data=>#<ActionDispatch::Http::UploadedFile:0x007ff871c261b0 @tempfile=#<Tempfile:/var/folders/xb/38dybzwn51g3fg4vb7kdgg5m0000gn/T/RackMultipart20160704-11159-5aarh7.mp3>, @original_filename="03 Exit Wounds (Original Mix).mp3", @content_type="audio/mp3", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"03 Exit Wounds (Original Mix).mp3\"\r\nContent-Type: audio/mp3\r\n">,:key=>"03 Exit Wounds (Original Mix).mp3")        Album Load (0.1ms)  SELECT  "albums".* FROM "albums" WHERE "albums"."id" = ? LIMIT 1  [["id", nil]]  Completed 404 Not Found in 16748ms (ActiveRecord: 0.9ms)    ActiveRecord::RecordNotFound (Couldn't find Album with 'id'=):    app/controllers/albums/songs_controller.rb:24:in `create'        Rendered /Users/sethjones/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (5.1ms)    Rendered /Users/sethjones/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)    Rendered /Users/sethjones/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (3.0ms)    Rendered /Users/sethjones/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (60.4ms)  Cannot render console with content type multipart/form-dataAllowed content types: [#<Mime::Type:0x007ff8731e25a8 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html">, #<Mime::Type:0x007ff8731e22d8 @synonyms=[], @symbol=:text, @string="text/plain">, #<Mime::Type:0x007ff8731dae20 @synonyms=[], @symbol=:url_encoded_form, @string="application/x-www-form-urlencoded">]  

ajax call redirect to page

Posted: 04 Jul 2016 05:37 AM PDT

In my server terminal I saw Started GET "/another" but the browser dont redirect to the url. What is wrong in this code?

Routes:

match '/example_url', to: 'controllerx#sup', via: 'get'  

Client side:

$.ajax({    type: "GET",// GET in place of POST    contentType: "application/json; charset=utf-8",    url: "/example_url",    data : {example: 'hey'},    success: function(result) {      //TODO    },    error: errorFunction  });  

Controller:

def sup    respond_to do |format|      format.js { redirect_to another_path }    end  end    

rails controller action AND javascript onclick

Posted: 04 Jul 2016 04:00 AM PDT

I am trying to do both: call a controller action and react to onclick with a javascript function. At the moment, I only can do one thing. Trying with

<%= button_to 'Call Action', contoller_action_path, :remote => true,                :method => 'post',                :onclick => "setSomeJsState('Run'); return(false);" %>  

it triggers only the onclick part. Any ideas? Thanks in advance, devyn

How to copy over /public folder of Rails Engine to a Rails application in production?

Posted: 04 Jul 2016 03:32 AM PDT

I know a simple solution would be just to manually copy over all the files in the Rails Engine's /public folder to the Rails application's /public folder. However, this means that each installation would require manually copying.

Furthermore because the Javascript files that my engine uses have hard-coded image paths, I cannot simply throw all my static files under app/assets or vendor/assets, as then Rails would copy them over to public/assets. I can't change the path where Sprockets outputs the files as I have other gems that expect their assets to be in the default public/assets folder.

I tried doing something like

    class Engine < ::Rails::Engine          if Rails.application.config.serve_static_assets              initializer "static assets" do |app|                app.middleware.insert_before(::ActionDispatch::Static, ::ActionDispatch::Static, "#{root}/public")              end          end      end  

but this only works for development.

Can't access another model through Active Record

Posted: 04 Jul 2016 03:44 AM PDT

I'm very new to ruby and to rails.

I've been stuck with this for days. I think I should be able to access a variable in a controller of one model, that is stored in another model easily?

I have four models: User - (1-1) - Profile - (1-M) - Appointment - (1-1) - Option.

Options contains pricePerPerson and discount for an appointment. Appointments contains, among others, numPeople. I want to access the figure in the Options model for the pricePerPerson (and discount, if appropriate) and use it in the view show for Appointments. (@ <%= appointment.price = Option.pricePerPerson * numPeople %>)

So far I haven't been able to do this and have had to resort to hard-coding a price per person. I would rather not hard-code that, if possible.

I thought I could do this either of the two ways:

1: as there is a belongs_to relationship between options and appointments - (Options belongs to appointments)

Appointments Controller:

def new     @appointment = Appointment.new     @appointment.price = option.appointment.pricePerPerson  end  

appointments/show.html.erb:

<p>    <strong>Price:</strong>    <%#= 5 * @appointment.numpeople %>    <%= @appointment.price * @appointment.numpeople %>  </p><br>  

2: Something like this:

Appointments Controller:

def new     @appointment = Appointment.new     pricePerPerson = params([:appointment])     price = Option.find(pricePerPerson)     @appointment.price = price.pricePerPerson  end  

I'm obviously very wrong on both counts, as I can't seem to get this working. I wonder if anyone can explain to me how I might go about solving this issue, or even point me in the right direction?

Rails serving files outside assets folder and public folder

Posted: 04 Jul 2016 04:45 AM PDT

Rails version: Rails 3.2.15

Ruby version: ruby 1.9.3p551 (2014-11-13 revision 48407)

Issue:

My rails app in development mode is serving files from storage folder which is at root level. The file format is pdf and mp4.

By serving i mean if I hit the route directly Eg: http://localhost:3000/assets/file_name.pdf is not throwing error and instead is opening on the browser.

I want to put these files behind authentication and hence tried putting it outside app/assets and public/ folders.

I'm not sure why is it able to serve any file outside those directories. Here are few of my configs for reference:

config.assets.enabled = true

config.assets.compress = false

config.assets.debug = true

Please help...

Rails - Rendering form_for @user in a different view

Posted: 04 Jul 2016 03:10 AM PDT

I'm trying to render this code (partial to update users payment info).

/devise/registrations/_credit.html.erb

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>  <form action="#">            <div class="form-group">                <label class="control-label">Card Holder Name</label>                <%= f.text_field :name, autofocus: true, class:"form-control" %></div>              <div class="form-group">                  <label class="control-label">Card Number</label>                  <%= f.text_field :card, autofocus: false, class:"form-control" %>              </div>              <div class="form-group">                  <label class="control-label">CVV</label>                  <%= f.text_field :cvv, autofocus: false, class:"form-control" %>              </div>              <div class="form-group">                  <label class="control-label">Expiration Month</label>                  <%= f.text_field :expmonth, autofocus: false, class:"form-control" %>              </div>              <div class="form-group">                  <label class="control-label">Expiration Year</label>                  <%= f.text_field :expyear, autofocus: false, class:"form-control" %>              </div>              <div class="margin-top-10">                   <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>                <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>              <% end %>                <div class="actions">                <%= f.submit "Update", class:"btn green" %>                <% end %>              </div>      </form>  </div>  

I'm trying to get this partial to show up in a different page that's not under users_controller.rb, but I keep getting an error.

NameError in Orders#new  Showing /home/nitrous/code/uvesty/app/views/devise/registrations/_credit.html.erb where line #2 raised:    undefined local variable or method `resource' for #<#<Class:0x00563138834928>:0x00563138821670>  

Undefined method `<<` in image upload

Posted: 04 Jul 2016 03:56 AM PDT

def create      @product = Product.find(1)      @product.images << params[:image]      @product.save  end  

The schema is

 t.string   "images",       default: [],              array: true  

I want the assign the image coming in params to the images array, if the image is already there. The new image should append, otherwise it should be the first one

Here is the Product model

class Product < ActiveRecord::Base      mount_uploader  :images, ProductUploader        validates :name, presence: true       validates :price, presence: true      validates :availability, presence: true      validates :about, presence: true      validates :ref, presence: true      validates :texture, presence: true      validates :shipping, presence: true      validates :category, presence: true      validates :notes, presence: true    end  

I generated the ProductUploader through carrierwave uploader command

class ProductUploader < CarrierWave::Uploader::Base      # Include RMagick or MiniMagick support:    # include CarrierWave::RMagick    # include CarrierWave::MiniMagick      # Choose what kind of storage to use for this uploader:    storage :file    # storage :fog      # Override the directory where uploaded files will be stored.    # This is a sensible default for uploaders that are meant to be mounted:    def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end      # Provide a default URL as a default if there hasn't been a file uploaded:    # def default_url    #   # For Rails 3.1+ asset pipeline compatibility:    #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))    #    #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')    # end      # Process files as they are uploaded:    # process scale: [200, 300]    #    # def scale(width, height)    #   # do something    # end      # Create different versions of your uploaded files:    # version :thumb do    #   process resize_to_fit: [50, 50]    # end      # Add a white list of extensions which are allowed to be uploaded.    # For images you might use something like this:    # def extension_whitelist    #   %w(jpg jpeg gif png)    # end      # Override the filename of the uploaded files:    # Avoid using model.id or version_name here, see uploader/store.rb for details.    # def filename    #   "something.jpg" if original_filename    # end    end  

After uploading the image, the image shows up in params. But does not get saved in the table. Here is the screenshot of byebug

enter image description here

Edit:

I have made some progress

I updated the string [] to json for images like this

And instead of files coming like string, it's coming as file. Now the only problem is, I am unable to access the name properly name=\"image[avatar_1]\" in the params

"utf8"=>"✓", "authenticity_token"=>"JbtcVdUvPJIzSHycX0wdr349zcATDN51vSewI33nvHIKQdhxxgxWUEJz9ZsubNrgvq2ftO+DosHXWM8Tipce7w==", "image"=>{"avatar_1"=>#<ActionDispatch::Http::UploadedFile:0x007f2ba8377f78 @tempfile=#<Tempfile:/tmp/RackMultipart20160704-20497-1czlw3s.png>, @original_filename="no-save.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"image[avatar_1]\"; filename=\"no-save.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"submit", "controller"=>"upload", "action"=>"create"}  

Here is the view file

<%= simple_form_for :image, method: :post, url: save_image_path do |f| %>            <%= f.file_field :avatar_1 %>            <%= f.submit :submit %>        <% end %>  

here it is avatar_1. I need to change it in create code, but I am not accessing params itself properly

Yaxis Value should be integer value it should not show the floating point values

Posted: 04 Jul 2016 02:13 AM PDT

Im using chartkick gem here to do this

contract_emp.html.erb  <%= column_chart emp_contracts, stacked: true, xtitle: "Contracts", ytitle: "Employee Count",allowDecimals: false, id: "contract_emp-chart-container"%>  

using allowDecimal values also im getting floating point values, can any one suggest me how to get integer value in the y-axis.

Rails, rendering a collection

Posted: 04 Jul 2016 07:37 AM PDT

I have to render a collection of orders like this:

= render partial: 'order_row', collection: @order_items, as: order_item  

In my partial I would have to use order_item.product multiple times. Is there a way to say that product is order_item.product? I tried with locals: {product: order_item.product} but it looks like the order_item can be used only in the rendered partial. In other words, how to translate this .each do block to a render.

  - @order_items.each do |order_item|      = render 'order_row', product: order_item.product, order_item: order_item  

Rails 4 - belong_to nested object fields are not saved

Posted: 04 Jul 2016 07:31 AM PDT

Note: I've read a couple posts similar to this. But non of the solutions works for me.
I have two objects Appeal and Appealer with one to many relationship. When I save the Appeal object all fields are saved and also the appealer id is saved (as FK). But in the Appealer table a new record is saved with no data except for id.

MODEL

class Appeal < ActiveRecord::Base      belongs_to :appealer, :autosave => true      accepts_nested_attributes_for :appealer  end    class Appealer < ActiveRecord::Base      has_many :appeals, :autosave => true  end  

AppealsController

class AppealsController < ApplicationController      def index          respond_with Appeal.all      end        def create          appealer = Appealer.create(appealer_params)          @appeal = Appeal.create(appeal_params)          @appeal.appealer = appealer              if @appeal.save            respond_with @appeal          else            respond_with {:error}          end      end        def show          respond_with Appeal.find(params[:id])      end        private      def appeal_params          params.require(:appeal).permit(:subject, :status, :submit_means, :card_type, :submit_date, :relationship, :report_date, :explanation, :email_approval)      end      def appealer_params          params.require(:appeal).permit(appealer: [:appealer_id, :first_name, :last_name])      end  end  

EDIT Here is the json I use

{          "id": 21,          "subject": "axxxscaaaa",          "status": "happy",          "submit_means": "DOAR",          "card_type": "sdsd",          "submit_date": 1466629200000,          "relationship": null,          "report_date": 1466542800000,          "explanation": "sdsd",          "email_approval": null,          "appealer": {"first_name":"aaaaaaa", "last_name":"fffff"},          "selfRequest": false,          "created_at": 1465851600000,          "updated_at": 1465333200000      }  

I don't understand why the fields of appealer are not saved

Coffeescript json response processing

Posted: 04 Jul 2016 02:32 AM PDT

I just starting with coffeescript. However, I have to process a JSON response from a rails app to generate google map markers. How do I parse the JSON data into the coffeescript.

Code looks like this:

  $.ajax '/locations',            type: 'GET'            dataType: 'json'            error: (jqXHR, textStatus, errorThrown) ->                alert "error"            success: (data, textStatus, jqXHR) ->                buses = data      window.initMap = ->      map = new google.maps.Map(document.getElementById('map'),        center:          lat: 0.324680          lng: 32.572633        zoom: 11      )    if buses?      for i in buses        marker = new google.maps.Marker(position: new google.maps.LatLng(i["latitude"], i["longitude"])        map: map        title: i["number_plate"])        marker.setMap(map)      loadScript = ->      script = document.createElement("script")      script.type = "text/javascript"      script.src = "https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxx&callback=initMap"      document.getElementById('map_scripts').appendChild script      return      loadScript()  

The Json response looks like this {"locations":[{"number_plate":"UAW796N","terminal_number":2,"latitude":"0.4122","longitude":"33.235","speed":"46.0"}]}

error in ruby on rails (rails g controller 'name')

Posted: 04 Jul 2016 01:14 AM PDT

have installed my ruby on rails but after running first program, i'm getting lots of error, like Warning: Running gem pristine --all to regenerate your installed gemspecs (and deleting then reinstalling your bundle if you use bundle --path) will improve the startup performance of Spring. Ignoring sqlite3-1.3.11 because its extensions are not built. Try: gem pristine sqlite3 --version 1.3.11 /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in require': cannot load such file -- bundler (LoadError) from /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:inrequire' from /var/lib/gems/2.1.0/gems/spring-1.7.1/lib/spring/client/run.rb:3:in <top (required)>' from /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:inrequire' from /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in require' from /var/lib/gems/2.1.0/gems/spring-1.7.1/lib/spring/client.rb:5:in' from /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in require' from /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:inrequire' from /var/lib/gems/2.1.0/gems/spring-1.7.1/bin/spring:48:in `' if you can help,will be helpful

How can I get the id from select tag as params?

Posted: 04 Jul 2016 01:48 AM PDT

I am a little bit confused in how can this params work. For example I trying to create a collections of users with select tag in index page like this:

users/index.html.erb

<%= select_tag "user", options_from_collection_for_select(@users, "id", "name")%>    <%= link_to "new", new_user_book_path(params[:user]) %>  

I have a dropdown with a list of users, and I have a button which links to books/new page. How can I pass the user id which I have selected in the dropdown to the 'new_user_book_path`?

Thanks in advance!

Efficient way to store all users into Redis instead of marshalling an array

Posted: 04 Jul 2016 01:06 AM PDT

I am current using Rails.cache.fetch, with the cache_store using redis-store gem (modified to use YAML instead of marshalling normally). Right now, I have the following code:

    Rails.cache.fetch("foobar", expires_in: 1.week) do        User.all.to_a.each do |user|         user.email = "foobar"        end      end  

This in will store a YAML version of a ruby array of Users into a single key value. I would like to efficiently break up this list into multiple keys, with the idea of being able to retrieve all the values later instead of hitting the database.

How should I do this? I was thinking about a list of hashes, but it doesn't seem efficient as I still would need to look up a specific hash in the list to update just one user.

No comments:

Post a Comment