Saturday, March 26, 2016

haml problems with conversion to html / erb | Fixed issues

haml problems with conversion to html / erb | Fixed issues


haml problems with conversion to html / erb

Posted: 26 Mar 2016 07:44 AM PDT

I would like to pass it to erb.

 %a.btn.btn-small.notes_campaign{:role => "button", :data => {:campaign_group_id => campaign_group.id}}     %i.icon-tasks     Notes   

My problem is this passage from the date later used in an ajax request. Already tried in various ways.

Has anyone ever experienced this?

How to delete file from 'public' directory in Rails 4?

Posted: 26 Mar 2016 07:24 AM PDT

How can i delete img files from '/public/posts/' directory in my project? I have a few images in this dir

-public  --posts  ---1.jpg  ---2.jpg  ---3jpg  

my model: Post.rb

before_destroy :remove_file  def remove_file   getAllImages.each do |file|    File.delete(Rails.root.join('public', file))   end  end  

Error:

Errno::ENOENT in PostsController#destroy    No such file or directory @ unlink_internal - /posts/1.jpg  

Turbolinks and Bootstrap Tab activation

Posted: 26 Mar 2016 07:21 AM PDT

I am basically facing the same problem as described here, under the additional context of Rails' Turbolinks.

I am using this piece of code

$(document).on('ready page:change', function() {      /* Show tab from anchor */      var hash = window.location.hash;      hash && $('ul.nav a[href="' + hash + '"]').tab('show');        /* Update URL anchor after selecting tab */      $('.nav-tabs a').click(function (e) {          $(this).tab('show');          var scrollmem = $('body').scrollTop();          window.location.hash = this.hash;          $('html,body').scrollTop(scrollmem);      });  

Which does work for manual page reload (F5) and for cache restore, but not after reloading the page from a Turbolinks click*.

*When clicking a turbolinks link, if there is some cache of the page, then that cache is first restored and the good tab is shown, but then thre is still a request to the server to get the last contents, and once that request arrives and is parsed, the tab "switches back" to the original one

My bootstrap code looks like this

<ul class="nav nav-tabs" role="tablist">      <li class="nav-item">      <a class="nav-link active" data-toggle="tab" href="#student" role="tab"></a>      </li>      <li class="nav-item">      <a class="nav-link" data-toggle="tab" href="#mentor" role="tab"><%= </a>      </li>      <li class="nav-item">      <a class="nav-link" data-toggle="tab" href="#company" role="tab"></a>      </li>  </ul>    <!-- Tab panes -->  <div class="tab-content">      <br />      <div class="tab-pane fade in active" id="student" role="tabpanel">          ...      </div>      <div class="tab-pane fade" id="mentor" role="tabpanel">          ...      </div>      <div class="tab-pane fade" id="company" role="tabpanel">          ...      </div>  </div>  

URL forwarding to subdomains on the fly (in Rails on Openshift)

Posted: 26 Mar 2016 07:54 AM PDT

My Rails app creates subdirectories i.e. mainDomain.com/data/usr1 but I need them to be accessible as subdomains like usr1.mainDomain.com. How does one set this up on Openshift to work ever time the app creates a directory? Is it even done in the Rails code?

Thanks for your help

Update: I'm trying to find out if this is something I should do at the Rails level or if it is done that the server "wildcard forwarding DNS" level?

Get App user access token using Koala and Rails

Posted: 26 Mar 2016 05:58 AM PDT

I have a Facebook app and I can get both its User Token and App Token from this url: https://developers.facebook.com/tools/access_token/ In my Ruby on Rails application I am getting event information using the following code:

graph = Koala::Facebook::API.new(<My USER token from the aforementioned URL>)  fb_event = graph.get_object(facebook_event_id)   

The issue here is that the app User Token expires. I know this is the reason why it should not be put directly in the code, but for testing purposes thus far it's been sufficient. However, this is obviously not a good long term strategy.

How can I dynamically obtain this User Token? Is it similar to getting a user token for an actual user as opposed to an app?

Rails 4 - heroku production version not incorporating js or images

Posted: 26 Mar 2016 07:08 AM PDT

I'm trying to figure out what's going wrong with my deployment in production to Heroku.

My local host files all work.

I have app/assets/js folder with a file called application.js, which has:

//= require jquery  //= require bootstrap-sprockets  //= require jquery_ujs  //= require html.sortable  //= require bootstrap-slider  //= require moment  //= require bootstrap-datetimepicker  //= require pickers  //= require main  //= require npm  //= require hammer.min  //= require jquery.animate-enhanced.min  //= require jquery.countTo  //= require jquery.easing.1.3  //= require jquery.fitvids  //= require jquery.magnific-popup.min  //= require jquery.parallax-1.1.3  //= require jquery.properload  //= require jquery.shuffle.modernizr.min  //= require jquery.sudoSlider.min  //= require jquery.superslides.min  //= require masonry.pkgd.min  //= require rotaterator  //= require smoothscrolljs  //= require waypoints.min  //= require wow.min  //= require underscore  //= require gmaps/google  //= require dependent-fields  //= require chosen-jquery  //= require cocoon  //= require imagesloaded.pkgd.min  //= require isotope.pkgd.min  //= require circle-progress  //= require jquery.counterup.min  //= require jquery.pjax  //= require custom.js  //= require_tree .  

In my app/assets/stylesheets folder. I have a file called application.css.scss, which has:

@import "bootstrap-sprockets";  @import "bootstrap";  @import 'bootstrap-datetimepicker';  @import "font-awesome-sprockets";  @import "font-awesome";  @import "bootstrap-slider";  @import "chosen";  @import "animate";  @import "magnific-popup";  @import "simple-line-icons";  @import "shortcodes";  @import "style";  @import "text";  @import "variable";      @import "addresses.scss";  @import "articles.scss";  @import "common.scss";  @import "footer.scss";  @import "forms.scss";  @import "glyphs.scss";  @import "index.scss";  @import "legal.scss";  @import "navigation.scss";  @import "pages.scss";  @import "profiles.scss";  @import "profile2.scss";  @import "video.scss";  

I also have app/assets/images folder. It has several .jpg and .png files as well as favicon.ico

In my application.rb, I have

require File.expand_path('../boot', __FILE__)    require 'rails/all'      # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)      class Application < Rails::Application      # Settings in config/environments/* take precedence over those specified here.      # Application configuration should go into files in config/initializers      # -- all .rb files in that directory are automatically loaded.        # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.      # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.      config.time_zone = 'London'        # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.      # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      # config.i18n.default_locale = :de        # Do not swallow errors in after_commit/after_rollback callbacks.      config.active_record.raise_in_transactional_callbacks = true        config.assets.paths << "#{Rails}/vendor/assets/fonts"        config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif)        config.assets.initialize_on_precompile = false        config.secret_key_base = Figaro.env.secret_key_base        # I18n.available_locales = [:en, :ru]        # config.active_record.observers = :video_observer        # config.active_record.observers = :user_observer        config.autoload_paths += %W(#{config.root}/services)    end  end  

In my production.rb, I have

# Enable Rack::Cache to put a simple HTTP cache in front of your application    # Add `rack-cache` to your Gemfile before enabling this.    # For large-scale production use, consider using a caching reverse proxy like    # NGINX, varnish or squid.    # config.action_dispatch.rack_cache = true      # Disable serving static files from the `/public` folder by default since    # Apache or NGINX already handles this.    config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?      # Compress JavaScripts and CSS.    config.assets.js_compressor = :uglifier    config.assets.css_compressor = :sass      # Do not fallback to assets pipeline if a precompiled asset is missed.    # config.serve_static_assets = true    # config.assets.compile = true    config.assets.precompile =  ['*.js']     # config.assets.precompile += %w(*.js *.css *.svg *.eot *.woff *.ttf *.gif *.png *.ico)        # Asset digests allow you to set far-future HTTP expiration dates on all assets,    # yet still be able to expire them through the digest params.    config.assets.digest = false      # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb      # Specifies the header that your server uses for sending files.    # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache    # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX      # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.    # config.force_ssl = true      # Use the lowest log level to ensure availability of diagnostic information    # when problems arise.    config.log_level = :debug      # Prepend all log lines with the following tags.    # config.log_tags = [ :subdomain, :uuid ]      # Use a different logger for distributed setups.    # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)      # Use a different cache store in production.    # config.cache_store = :mem_cache_store      # Enable serving of images, stylesheets, and JavaScripts from an asset server.    # config.action_controller.asset_host = 'http://assets.example.com'      # Ignore bad email addresses and do not raise email delivery errors.    # Set this to true and configure the email server for immediate delivery to raise delivery errors.    # config.action_mailer.raise_delivery_errors = false      # Enable locale fallbacks for I18n (makes lookups for any locale fall back to    # the I18n.default_locale when a translation cannot be found).    config.i18n.fallbacks = true      # Send deprecation notices to registered listeners.    config.active_support.deprecation = :notify      # Use default logging formatter so that PID and timestamp are not suppressed.    config.log_formatter = ::Logger::Formatter.new      # Do not dump schema after migrations.    config.active_record.dump_schema_after_migration = false  

In my config initialiser/assets.rb file I have:

# Be sure to restart your server when you modify this file.    # Version of your assets, change this if you want to expire all your assets.  Rails.application.config.assets.version = '1.0'    # Add additional assets to the asset load path  # Rails.application.config.assets.paths << Emoji.images_path    # Precompile additional assets.  # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.  Rails.application.config.assets.precompile += %w( search.js )  Rails.application.config.assets.precompile += %w( surveyor_all.js )  Rails.application.config.assets.precompile += %w( surveyor_all.css )  Rails.application.config.assets.precompile += %w( index.css )  Rails.application.config.assets.precompile += %w( *.jpg *.gif *.png *.ico )  Rails.application.config.assets.precompile += %w( favicon.ico )  Rails.application.config.assets.precompile += %w( application.css )  

I have tried several times over running rake precompile assets and to run RAILS_ENV=production bundle exec rake assets:precompile. I can't get anything to work.

The javascript that works fine in the development version doesn't work in production. Images are not rendering. I cannot figure out why. All js files used in the application are listed in application.js. Some of the required files are stored in the vendor folder. Similarly, all css files are listed in the application.css.scss file and all images are in app assets images folder.

Does anyone know how to deploy to Heroku with all files included?

Examples (there are many, of things that don't work:

  1. Image

    " >

The above image is stored in my app assets images folder. It just renders a blank panel (in production).

  1. CSS

I have a panel of content with div tabs and ids. The tabs are supposed to move when an id is clicked. They don't, the panel is stuck on the first tab:

<div class="row">                          <div class="col-md-12">                              <div class="dp-tab-1">                                  <ul class="dp-tab-list row" id="myTab">                                      <li class="col-md-3 col-xs-6 active" >                                          <a href="#tab-content-first">                                                <span>THE OLD WAY</span>                                          </a>                                      </li>                                      <li class="col-md-3 col-xs-6">                                          <a href="#tab-content-second">                                                <span>direct</span>                                          </a>                                      </li>                                      <li class="col-md-3 col-xs-6">                                          <a href="#tab-content-third">                                                    <span>MYTHs</span>                                          </a>                                      </li>                                      <li class="col-md-3 col-xs-6">                                          <a href="#tab-content-fourth">                                                <span>OUR APPROACH</span>                                          </a>                                      </li>                                  </ul>                                  <div class="dp-tab-content tab-content">                                      <div class="tab-pane row fade in active" id="tab-content-first">                                          <div class="col-md-6 text-center">                                                <%= image_tag "oldway.jpg", :class=>"wow fadeInLeft img-responsive", :alt=>"The old fashioned way" %>                                            </div>                                          <div class="col-md-6">                                              <div class="tab-inner">                                                  <h4> INEFFICIENT</h4>                                                  <p class='medium-text'>                                                      With:                                                      <ul class='medium-text'>                                                          <li class='medium-text'>- grant  routinely dwarfed                                                       </ul>                                                       </p>                                                    <p class='medium-text'>                                                      It's beyond clear, that                                                   </p>                                                      <br/>                                                  <a class='btn btn-info btn-line'>READ MORE</a>                                              </div>                                          </div>                                      </div>                                      <div class="tab-pane row fade" id="tab-content-second">                                          <div class="col-md-8">                                              <div class="tab-inner">  
  1. JS

        <span class="countTo" data-from="356" data-to="0" data-speed="3000">0</span>      </div>  

Can't get item from a JSON response

Posted: 26 Mar 2016 05:52 AM PDT

I'm currently using HTTParty to GET a API endpoint, when testing it within console it seems to be coming up with 'undefined method `[]' for nil:NilClass'.

This is the steps I'm taking:

response = HTTParty.get("https://api.import.io/store/connector/ab589079-436a-47da-923c-c77cb572491d/_query?input=webpage/url:http%3A%2F%2Flinxspiration.com%2F%23_%3D_&&_apikey=dc9014801ce443229a302ec1db31bc7683360af6669d43767164345452e9faef39e958817471e8c77f894d1032293acc8656cefa3df03123ee06a331f313c7f131ed345f4bf0fa8f460a80a6e9c4cbc1")  

Which returns

#<HTTParty::Response:0x5231220 parsed_response={"offset"=>0, "results"=>[{"tags_link"=>"http://linxspiration.com/tagged/women", "date_link_numbers/_source"=>"53", "media_images/_alt"=>"by Joakim Karlsson", "block_content"=>"by Joakim Karlsson", "date_link"=>"http://linxspiration.com/post/141713637264/by-joakim-karlsson", "media_images"=>"http://40.media.tumblr.com/22ef0cc5c89400be3346de71eaff7333/tumblr_o4lw3rLlhi1qkegsbo1_1280.jpg", "date_link_numbers"=>53.0, "likes_link_numbers"=>73.0, "blazepress_link"=>"http://t.umblr.com/redirect?z=https%3A%2F%2F500px.com%2Fjoakimkarlssonphotography&t=NjhiYmIxZDdmZTk2Y2Q1YmQ0ZjE5Nzg2ZjAxMjU1MWQwZmY5NjBhNCxkTFNrT2c2Tw%3D%3D", "likes_link/_title"=>"73 notes", "tags_link/_text"=>"#women", "likes_link/_text"=>"73 notes", "blazepress_link/_text"=>"Joakim Karlsson", "date_link/_text"=>"53 minutes ago", "media_link"=>"http://linxspiration.com/post/141713637264/by-joakim-karlsson", "likes_link_numbers/_source"=>"73", "date_link/_title"=>"53 minutes ago", "likes_link"=>"http://linxspiration.com/post/141713637264/by-joakim-karlsson#notes"}, {"date_link_numbers/_source"=>"2", "blockquote_content"=>"City Skylines. Buy this poster. linxsupply.com", "media_images/_alt"=>"linxsupply:\n\nCity Skylines.\nBuy this poster.\nlinxsupply.com", "block_content"=>"linxsupply:", "date_link"=>"http://linxspiration.com/post/141711949548/linxsupply-city-skylines-buy-this-poster", "media_images"=>"http://40.media.tumblr.com/adb42e7317096b5f2884314110c6594f/tumblr_o0mxowUg7e1uhpqwfo1_1280.jpg", "date_link_numbers"=>2.0, "content_link"=>["http://t.umblr.com/redirect?z=https%3A%2F%2Flinxsupply.com%2Fproduct%2Fcity-skylines%2F&t=NGE5M2YxZDRhYTkyNjIzOTFkYmMxZjg3YjUxZGY1YWE1MTg0MmVmNSxscnB6Y2p2cQ%3D%3D", "http://t.umblr.com/redirect?z=https%3A%2F%2Flinxsupply.com%2Fproduct%2Fcity-skylines%2F&t=NGE5M2YxZDRhYTkyNjIzOTFkYmMxZjg3YjUxZGY1YWE1MTg0MmVmNSxscnB6Y2p2cQ%3D%3D", "http://t.umblr.com/redirect?z=http%3A%2F%2Flinxsupply.com&t=ZDcxZDIwY2I2NDg5YzM0NjY1YjgxYmY1NWYxYTFhNDE0Y2EyN2Y4ZCxscnB6Y2p2cQ%3D%3D"], "likes_link_numbers"=>2108.0, "blazepress_link"=>"http://linxsupply.tumblr.com/post/136877431779", "likes_link/_title"=>"2,108 notes", "likes_link/_text"=>"2,108 notes", "blazepress_link/_text"=>"linxsupply", "date_link/_text"=>"2 hours ago", "media_link"=>"http://linxspiration.com/post/141711949548/linxsupply-city-skylines-buy-this-poster", "likes_link_numbers/_source"=>"2,108", "date_link/_title"=>"2 hours ago", "likes_link"=>"http://linxspiration.com/post/141711949548/linxsupply-city-skylines-buy-this-poster#notes", "content_link/_text"=>["City Skylines.", "Buy this poster.", "linxsupply.com"]}, {"date_link_numbers/_source"=>"3", "blockquote_content"=>"Linx Snapback Buy this hat linxsupply.com", "media_images/_alt"=>"linxsupply:\n\nLinx Snapback\nBuy this hat\nlinxsupply.com", "block_content"=>"linxsupply:", "date_link"=>"http://linxspiration.com/post/141710261817/linxsupply-linx-snapback-buy-this-hat", "media_images"=>"http://36.media.tumblr.com/09692725db89595d54cb7ad6e47e8cff/tumblr_o0pifybRpl1uhpqwfo1_1280.jpg", "date_link_numbers"=>3.0, "content_link"=>["http://t.umblr.com/redirect?z=https%3A%2F%2Flinxsupply.com%2Fproduct%2Flinx-outline-snapback%2F&t=Mjk1YTEyMzZhMzFkYzRjYjBkZjAzYmMwOGI1NWY5MTdjM2NhMWE1OCxDbGN2RThHbQ%3D%3D", "http://t.umblr.com/redirect?z=https%3A%2F%2Flinxsupply.com%2Fproduct%2Flinx-outline-snapback%2F&t=Mjk1YTEyMzZhMzFkYzRjYjBkZjAzYmMwOGI1NWY5MTdjM2NhMWE1OCxDbGN2RThHbQ%3D%3D", "http://t.umblr.com/redirect?z=http%3A%2F%2Flinxsupply.com&t=M2EwZDIyN2YwZWZlNGZhMGMwMGUzNDhkNzkyMGY5YWVjYWQ0MDdkMCxDbGN2RThHbQ%3D%3D"], "likes_link_numbers"=>86.0, "blazepress_link"=>"http://linxsupply.tumblr.com/post/136972374084", "likes_link/_title"=>"86 notes", "likes_link/_text"=>"86 notes", "blazepress_link/_text"=>"linxsupply", "date_link/_text"=>"3 hours ago", "media_link"=>"http://linxspiration.com/post/141710261817/linxsupply-linx-snapback-buy-this-hat", "likes_link_numbers/_source"=>"86", "date_link/_title"=>"3 hours ago", "likes_link"=>"http://linxspiration.com/post/141710261817/linxsupply-linx-snapback-buy-this-hat#notes", "content_link/_text"=>["Linx Snapback", "Buy this hat", "linxsupply.com"]}, {"date_link_numbers/_source"=>"4", "blockquote_content"=>"Buy This Poster linxsupply.com", "media_images/_alt"=>"linxsupply:\n\nBuy This Poster\nlinxsupply.com", "block_content"=>"linxsupply:", "date_link"=>"http://linxspiration.com/post/141708477302/linxsupply-buy-this-poster-linxsupplycom", "media_images"=>"http://36.media.tumblr.com/826c6605838904baae1395263ce4bff1/tumblr_o1enzn1amD1uhpqwfo1_1280.jpg", "date_link_numbers"=>4.0, "content_link"=>["http://t.umblr.com/redirect?z=https%3A%2F%2Flinxsupply.com%2Fproduct%2Fretro%2F&t=ZDJmYmFkMGRlN2RjNzgwZWMzYzAwZmJjZWRkMThhNmY3MjhlMTI4OSx2S3gyZ25GVA%3D%3D", "http://t.umblr.com/redirect?z=http%3A%2F%2Flinxsupply.com&t=ZTYxMzU5Yzg4ODAyYTk0MGY0ZmU5MjFkOTRlMmJiYWZjZTM3YzA2Yix2S3gyZ25GVA%3D%3D"], "likes_link_numbers"=>352.0, "blazepress_link"=>"http://linxsupply.tumblr.com/post/137874566104", "likes_link/_title"=>"352 notes", "likes_link/_text"=>"352 notes", "blazepress_link/_text"=>"linxsupply", "date_link/_text"=>"4 hours ago", "media_link"=>"http://linxspiration.com/post/141708477302/linxsupply-buy-this-poster-linxsupplycom", "likes_link_numbers/_source"=>"352", "date_link/_title"=>"4 hours ago", "likes_link"=>"http://linxspiration.com/post/141708477302/linxsupply-buy-this-poster-linxsupplycom#notes", "content_link/_text"=>["Buy This Poster", "linxsupply.com"]}, {"date_link_numbers/_source"=>"5", "blockquote_content"=>"Delicate Ink Drawings on a Miniature Scale by Christian Watson", "date_link/_text"=>"5 hours ago", "likes_link_numbers/_source"=>"303", "block_content"=>"blazepress:", "date_link"=>"http://linxspiration.com/post/141706441055/blazepress-delicate-ink-drawings-on-a-miniature", "date_link/_title"=>"5 hours ago", "media_images"=>["http://41.media.tumblr.com/373bf8dcf6f9b6add8059590d1af2faf/tumblr_o4i0wj8BVV1tq9q5vo1_500.jpg", "http://41.media.tumblr.com/db57dad8b359f2aa077bb1b839b7e2ec/tumblr_o4i0wj8BVV1tq9q5vo2_500.jpg", "http://41.media.tumblr.com/623bddbeb3d82f161fed8f947d365a95/tumblr_o4i0wj8BVV1tq9q5vo3_500.jpg"], "date_link_numbers"=>5.0, "content_link"=>"http://t.umblr.com/redirect?z=http%3A%2F%2Fblazepress.com%2F2016%2F03%2Fdelicate-ink-drawings-on-a-miniature-scale-by-christian-watson%2F&t=MWUzODY3MWYxZDU4OWEyNDhiYWE2NDUzZDk5N2ZlODFlNDdhMTkyMixqRDZ6dVFTRQ%3D%3D", "likes_link_numbers"=>303.0, "likes_link"=>"http://linxspiration.com/post/141706441055/blazepress-delicate-ink-drawings-on-a-miniature#notes", "blazepress_link"=>"http://blazepress.tumblr.com/post/141607191351", "likes_link/_title"=>"303 notes", "likes_link/_text"=>"303 notes", "content_link/_text"=>"Delicate Ink Drawings on a Miniature Scale by Christian Watson", "blazepress_link/_text"=>"blazepress"}, {"tags_link"=>"http://linxspiration.com/tagged/women", "date_link_numbers/_source"=>"6", "media_images/_alt"=>"by Stef Hartog", "block_content"=>"by Stef Hartog", "date_link"=>"http://linxspiration.com/post/141703981640/by-stef-hartog", "media_images"=>"http://36.media.tumblr.com/c843e71790a636a6e149d8c70df98223/tumblr_o4lvsoKZ301qkegsbo1_1280.png", "date_link_numbers"=>6.0, "likes_link_numbers"=>112.0, "blazepress_link"=>"http://t.umblr.com/redirect?z=https%3A%2F%2F500px.com%2Fphoto%2F136087669%2Fkim-and-calvin-by-stef-hartog%3Fctx_page%3D1%26from%3Duser%26user_id%3D6609624&t=ZDRjY2U0ZGQ2NmRjNzdkZGMzYTdjMmVmNjMzZDQ1NWQ4YjM3NzJjZCxXVHRtRVVCVw%3D%3D", "likes_link/_title"=>"112 notes", "tags_link/_text"=>"#women", "likes_link/_text"=>"112 notes", "blazepress_link/_text"=>"Stef Hartog", "date_link/_text"=>"6 hours ago", "media_link"=>"http://linxspiration.com/post/141703981640/by-stef-hartog", "likes_link_numbers/_source"=>"112", "date_link/_title"=>"6 hours ago", "likes_link"=>"http://linxspiration.com/post/141703981640/by-stef-hartog#notes"}, {"date_link_numbers/_source"=>"7", "blockquote_content"=>"Russia.", "media_images/_alt"=>"blazepress:\n\nRussia.", "block_content"=>"blazepress:", "date_link"=>"http://linxspiration.com/post/141701003183/blazepress-russia", "media_images"=>"http://41.media.tumblr.com/f183cfc29d82696d008bb2c0631bc75e/tumblr_o4k8lsBGAh1tq9q5vo1_1280.jpg", "date_link_numbers"=>7.0, "content_link"=>"http://t.umblr.com/redirect?z=http%3A%2F%2Fi.imgur.com%2F791rugC.jpg&t=NTA1MjYwMWUyMWNiMmZkOGMwMmU2ZGU4MTAzYzVmY2MwY2RlZDFmOCxLYlM4UVNDcw%3D%3D", "likes_link_numbers"=>178.0, "blazepress_link"=>"http://blazepress.tumblr.com/post/141625099144", "likes_link/_title"=>"178 notes", "likes_link/_text"=>"178 notes", "blazepress_link/_text"=>"blazepress", "date_link/_text"=>"7 hours ago", "media_link"=>"http://linxspiration.com/post/141701003183/blazepress-russia", "likes_link_numbers/_source"=>"178", "date_link/_title"=>"7 hours ago", "likes_link"=>"http://linxspiration.com/post/141701003183/blazepress-russia#notes", "content_link/_text"=>"Russia."}, {"date_link_numbers/_source"=>"8", "date_link/_text"=>"8 hours ago", "media_link"=>"http://linxspiration.com/post/141697715602", "likes_link_numbers/_source"=>"69", "date_link"=>"http://linxspiration.com/post/141697715602", "date_link/_title"=>"8 hours ago", "media_images"=>"http://41.media.tumblr.com/4cd79c44ceb0c297aa491475cb822039/tumblr_o4lvr0p5RD1qkegsbo1_1280.jpg", "date_link_numbers"=>8.0, "likes_link_numbers"=>69.0, "likes_link"=>"http://linxspiration.com/post/141697715602#notes", "likes_link/_title"=>"69 notes", "likes_link/_text"=>"69 notes"}, {"date_link_numbers/_source"=>"10", "date_link/_text"=>"10 hours ago", "media_link"=>"http://linxspiration.com/post/141694470674", "likes_link_numbers/_source"=>"228", "date_link"=>"http://linxspiration.com/post/141694470674", "date_link/_title"=>"10 hours ago", "media_images"=>"http://41.media.tumblr.com/cd42ef60f6e7222c96a6fc460a68116f/tumblr_o4lvpfZMfg1qkegsbo1_1280.jpg", "date_link_numbers"=>10.0, "likes_link_numbers"=>228.0, "likes_link"=>"http://linxspiration.com/post/141694470674#notes", "likes_link/_title"=>"228 notes", "likes_link/_text"=>"228 notes"}, {"tags_link"=>"http://linxspiration.com/tagged/landscape", "date_link_numbers/_source"=>"11", "media_images/_alt"=>"San Diego", "block_content"=>"San Diego", "date_link"=>"http://linxspiration.com/post/141691352399/san-diego", "media_images"=>"http://41.media.tumblr.com/497518d0508e5c833b780dec7e338a10/tumblr_o4lvleY3aB1qkegsbo1_1280.jpg", "date_link_numbers"=>11.0, "likes_link_numbers"=>108.0, "blazepress_link"=>"http://t.umblr.com/redirect?z=https%3A%2F%2F500px.com%2Fphoto%2F145836605%2Fsun-diego-by-kyle-kuiper%3Fctx_page%3D1%26from%3Duser%26user_id%3D13957979&t=NjQ0MTE5YzBjYjcwODExYjNlNWYxZWQ0ZDg2NTc5NDc0NDlkYjk5YSxpTHdTUTBocg%3D%3D", "likes_link/_title"=>"108 notes", "tags_link/_text"=>"#landscape", "likes_link/_text"=>"108 notes", "blazepress_link/_text"=>"San Diego", "date_link/_text"=>"11 hours ago", "media_link"=>"http://linxspiration.com/post/141691352399/san-diego", "likes_link_numbers/_source"=>"108", "date_link/_title"=>"11 hours ago", "likes_link"=>"http://linxspiration.com/post/141691352399/san-diego#notes"}, {"date_link_numbers/_source"=>"13", "date_link/_text"=>"13 hours ago", "media_link"=>"http://linxspiration.com/post/141685016105", "likes_link_numbers/_source"=>"102", "date_link"=>"http://linxspiration.com/post/141685016105", "date_link/_title"=>"13 hours ago", "media_images"=>"http://36.media.tumblr.com/d0bc7f18de3bba62fce33b9568ecbeab/tumblr_o4lvghfaCp1qkegsbo1_1280.jpg", "date_link_numbers"=>13.0, "likes_link_numbers"=>102.0, "likes_link"=>"http://linxspiration.com/post/141685016105#notes", "likes_link/_title"=>"102 notes", "likes_link/_text"=>"102 notes"}, {"date_link_numbers/_source"=>"14", "date_link/_text"=>"14 hours ago", "media_link"=>"http://linxspiration.com/post/141681640223", "likes_link_numbers/_source"=>"93", "date_link"=>"http://linxspiration.com/post/141681640223", "date_link/_title"=>"14 hours ago", "media_images"=>"http://41.media.tumblr.com/19577ca526da664fa5a3b3a49b87ada2/tumblr_o4lvfg6v1n1qkegsbo1_1280.jpg", "date_link_numbers"=>14.0, "likes_link_numbers"=>93.0, "likes_link"=>"http://linxspiration.com/post/141681640223#notes", "likes_link/_title"=>"93 notes", "likes_link/_text"=>"93 notes"}, {"tags_link"=>"http://linxspiration.com/tagged/women", "date_link_numbers/_source"=>"15", "media_images/_alt"=>"by Sean Archer", "block_content"=>"by Sean Archer", "date_link"=>"http://linxspiration.com/post/141678296075/by-sean-archer", "media_images"=>"http://41.media.tumblr.com/0a39d9ee6540da7bc86e80e0df88048c/tumblr_o4lvdoIiAo1qkegsbo1_1280.png", "date_link_numbers"=>15.0, "likes_link_numbers"=>130.0, "blazepress_link"=>"http://t.umblr.com/redirect?z=https%3A%2F%2F500px.com%2Fphoto%2F123406077%2Fanna-by-sean-archer%3Fctx_page%3D2%26from%3Duser%26user_id%3D777395&t=NGU3MmYwOTM3ODFkZDhiNWVlYjIxOTJmNmVjZDgzOWEyMjhjYjRjYyxTY3Mzdk90TA%3D%3D", "likes_link/_title"=>"130 notes", "tags_link/_text"=>"#women", "likes_link/_text"=>"130 notes", "blazepress_link/_text"=>"Sean Archer", "date_link/_text"=>"15 hours ago", "media_link"=>"http://linxspiration.com/post/141678296075/by-sean-archer", "likes_link_numbers/_source"=>"130", "date_link/_title"=>"15 hours ago", "likes_link"=>"http://linxspiration.com/post/141678296075/by-sean-archer#notes"}, {"date_link_numbers/_source"=>"16", "blockquote_content"=>"Hidden town, Monemvasia, Greece.", "media_images/_alt"=>"blazepress:\n\nHidden town, Monemvasia, Greece.", "block_content"=>"blazepress:", "date_link"=>"http://linxspiration.com/post/141675015276/blazepress-hidden-town-monemvasia-greece", "media_images"=>"http://41.media.tumblr.com/2a0d94dcc910d6e2ba9c1524279af560/tumblr_o4k8p3P4N41tq9q5vo1_1280.jpg", "date_link_numbers"=>16.0, "likes_link_numbers"=>574.0, "blazepress_link"=>"http://blazepress.tumblr.com/post/141627814665", "likes_link/_title"=>"574 notes", "likes_link/_text"=>"574 notes", "blazepress_link/_text"=>"blazepress", "date_link/_text"=>"16 hours ago", "media_link"=>"http://linxspiration.com/post/141675015276/blazepress-hidden-town-monemvasia-greece", "likes_link_numbers/_source"=>"574", "date_link/_title"=>"16 hours ago", "likes_link"=>"http://linxspiration.com/post/141675015276/blazepress-hidden-town-monemvasia-greece#notes"}, {"date_link_numbers/_source"=>"18", "blockquote_content"=>"A Coffee Table so Cool You'll Immediately Want One in Your Own Home", "date_link/_text"=>"18 hours ago", "likes_link_numbers/_source"=>"395", "block_content"=>"blazepress:", "date_link"=>"http://linxspiration.com/post/141671795034/blazepress-a-coffee-table-so-cool-youll", "date_link/_title"=>"18 hours ago", "media_images"=>["http://41.media.tumblr.com/57fc5fb22a35bb7f7be48e5f80e61ec8/tumblr_o4k98zdE3v1tq9q5vo1_500.jpg", "http://41.media.tumblr.com/240d4cf9ff2cd27b2e617c402bd06b24/tumblr_o4k98zdE3v1tq9q5vo2_500.jpg", "http://36.media.tumblr.com/c42f6d0c4c4b6d4cf0fcd30092d9bde7/tumblr_o4k98zdE3v1tq9q5vo3_500.jpg"], "date_link_numbers"=>18.0, "content_link"=>"http://t.umblr.com/redirect?z=http%3A%2F%2Fblazepress.com%2F2016%2F03%2Fa-coffee-table-so-cool-youll-immediately-want-one-in-your-own-home%2F&t=NDM5NDlmZDBhNDllNWRlYjcyYWUwYzdkOGM2NzZmMTUyNjg1OTk0NyxldldQSWpuRA%3D%3D", "likes_link_numbers"=>395.0, "likes_link"=>"http://linxspiration.com/post/141671795034/blazepress-a-coffee-table-so-cool-youll#notes", "blazepress_link"=>"http://blazepress.tumblr.com/post/141640731260", "likes_link/_title"=>"395 notes", "likes_link/_text"=>"395 notes", "content_link/_text"=>"A Coffee Table so Cool You'll Immediately Want One in Your Own Home", "blazepress_link/_text"=>"blazepress"}], "cookies"=>[], "connectorVersionGuid"=>"84aaf0b4-2bed-5469-f8ff-a7e8c0467082", "connectorGuid"=>"ab589079-436a-47da-923c-c77cb572491d", "pageUrl"=>"http://linxspiration.com/#_=_", "outputProperties"=>[{"name"=>"media_images", "type"=>"IMAGE"}, {"name"=>"media_link", "type"=>"URL"}, {"name"=>"block_content", "type"=>"STRING"}, {"name"=>"blazepress_link", "type"=>"URL"}, {"name"=>"blockquote_content", "type"=>"STRING"}, {"name"=>"content_link", "type"=>"URL"}, {"name"=>"tags_link", "type"=>"URL"}, {"name"=>"date_link", "type"=>"URL"}, {"name"=>"date_link_numbers", "type"=>"DOUBLE"}, {"name"=>"likes_link", "type"=>"URL"}, {"name"=>"likes_link_numbers", "type"=>"DOUBLE"}]}, @response=#<Net::HTTPOK 200 OK readbody=true>, @headers={"content-type"=>["application/json; charset=UTF-8"], "date"=>["Sat, 26 Mar 2016 12:20:14 GMT"], "server"=>["openresty/1.9.7.3"], "vary"=>["Accept-Encoding, User-Agent"], "content-length"=>["3615"], "connection"=>["Close"]}>  

Then I try to call an element within this parsed array like so:

puts response[0]["media_images"]  

Which returns

NoMethodError:undefined method `[]' for nil:NilClass

Getting current_user undefined method while using devise gem - Ruby on Rails 4.1.5

Posted: 26 Mar 2016 06:10 AM PDT

I'm following tutorial: https://www.youtube.com/watch?v=7-1HCWbu7iU I already did Pintrest clone using devise gem and had no issue. When I try to add current_user to links controller I get "undefined method current_user". I tried everything... even redoing the app from scratch, defining current_user, resetting the database. I guess the gem should handle the method automatically, right?

Here are my steps:

1. Generate new app - rails new raddit  2. Generate scaffold: rails g scaffold link title:string url:string  3. rake db:migrate  4. add gem 'devise', '~> 3.3.0' to gem file and run bundle install  5. run rails g devise:install  6. add file to development.rb - config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }  7. add alerts to layout/application.html (as per devise documentation)  8. generate view file - rails g devise:views  9. generate user - rails g devise User  10. rake db:migrate  11. rails s  12. go to localhost:3000/users/sign_up (works ok)  13. Add relation to models: user.rb - has_many :links ; link.rb -   belongs_to :user  14. Create migration: rails generate migration add_user_id_to_links user_id:integer:index  15. rake db:migrate  16. go to rails console and save assocation between user and links.  17. Add current_user to links controller - Getting undefined 'curren_user method' once I go to localhost:3000/links/new  

Here is my code:

  class LinksController < ApplicationController    before_action :set_link, only: [:show, :edit, :update, :destroy]      def index       @links = Link.all    end      def show    end      def new      @link = Link.current_user.links.build    end      def edit    end      def create      @link = current_user.build(link_params)        respond_to do |format|        if @link.save          format.html { redirect_to @link, notice: 'Link was       successfully created.' }           format.json { render :show, status: :created, location:  @link }        else           format.html { render :new }           format.json { render json: @link.errors, status: :unprocessable_entity }        end      end    end        def update      respond_to do |format|        if @link.update(link_params)          format.html { redirect_to @link, notice: 'Link was successfully updated.' }          format.json { render :show, status: :ok, location: @link }        else          format.html { render :edit }          format.json { render json: @link.errors, status: :unprocessable_entity }        end      end    end      def destroy         @link.destroy         respond_to do |format|         format.html { redirect_to links_url, notice: 'Link was successfully destroyed.' }        format.json { head :no_content }      end    end      private        def set_link        @link = Link.find(params[:id])      end       def link_params        params.require(:link).permit(:title, :url)     end     end  

My models: link.rb

class Link < ActiveRecord::Base      belongs_to :user  end  

My models: user.rb

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable    has_many :links  end  

Rails html.erb Select input convert to Slim

Posted: 26 Mar 2016 07:12 AM PDT

I am trying to convert all my html.erb files into .slim in my new project. I am missing last one inside of my form - a select input.

The form.html.erb looks

<%= form_for @user do |f| %>     <%= f.hidden_field :document_id, value: @doc.id %>       <%= f.label :Obor %>     <%= select(:user, :job, [         ["Choose work"],         ["Admin"],         ["Other"]         ],  {disabled: "Choose work", selected: "Choose work"}, class: "form") %>        <%= f.button "Submit" %>  <% end%>  

Everything works just in the way I want. I tried to make it in a .slim in this way:

= form_for @user do |f|     = f.hidden_field :document_id, value: @doc.id       = f.label :Obor     = select(:user, :job, [         ["Choose work"],         ["Admin"],         ["Other"]         ],  {disabled: "Choose work", selected: "Choose work"}, class: "form")        = f.button "Submit"  

It does not work with an error: Unknown line indicator ->

new.slim, Line xx, Column xx      ["Choose work"]  

How I can convert the select from html.erb into .slim? Thank you.

Rails routing and Knock

Posted: 26 Mar 2016 04:08 AM PDT

This question may be a bit trivial, but I'm new in rails. I use Knock to authenticate api users with JWT, and my routes.rb looks like this:

Rails.application.routes.draw do    resources :news_articles      mount Knock::Engine => "/sessions"  end  

According to knock docs, it creates a route 'POST /sessions/auth_token', how can i alias 'POST /sessions/auth_token' to just 'POST /sessions' via rails conf?

use min or max with active record

Posted: 26 Mar 2016 05:51 AM PDT

I am trying to get a min value from our database with the query below:

@supplier = Supplier.joins(:products).where('suppliers.permalink = ?', params[:id]).group('suppliers.id','products.id','products.name',min(variants.price)).pluck('products.id','products.name','suppliers.id',min(variants.price))  

when I run what I believe the query should be, I get this result:

SELECT suppliers.id as supp_id, products.id as prod_id, products.name as prod_name, min(price) as low_price, max(price) as high_price from suppliers    INNER JOIN variant_suppliers on variant_suppliers.supplier_id = suppliers.id    INNER JOIN variants on variants.id = variant_suppliers.variant_id    INNER JOIN products on products.id = variants.product_id  WHERE suppliers.id in (1,2)  GROUP BY suppliers.id, products.name, products.id;  

Using link_to helper to link to a parent view from child view - Ruby on Rails

Posted: 26 Mar 2016 05:15 AM PDT

So basically I'm trying to use link_to helper to link to a parent view from a child view.

I have the current relationship

Place has_many :experiences  Experience belongs_to :place  

In my experience view(show.html.erb) I have a button that I want to link to a place view. Currently, this experience is associated to a place (Parent being place and experience being the child)

<%= link_to 'Place', @place %>  

My experience controller

def show     @place = Place.find(params[:id])  end  

I get the following error

Couldn't find Experience with 'id'=Place

I'm not sure how to craft the @place to link to a place id. So how would I call a place view from the experience view?

f.collection_select with name

Posted: 26 Mar 2016 02:29 AM PDT

I hope someone can help me. I have a table with the name "location_location_relationships". If you create a new entry you can select two locations (predecessor and successor) which are from a "locaions" table. In addition you can select a tour. These are coming from table "tours". The locations selection is working. But the tours makes some problems. First I had nothing in the models everything worked but the selection wrote not the names but the ids in the "location_location_relationships" table. But I want the names in there. So I completed the models of "tours" and "location_location_relationships". In the selection there are the names of the tours now but if I press the Button "create" I get an error massage: Tour(#96769428) expected, got String(#1848192)

and it shows me the error in the location_location_relationship_controller.rb in: 'def create

@location_location_relationship = LocationLocationRelationship.new(location_location_relationship_params)'  

Has anyone an idea what I did wrong?

Thank you very much for your help in advance!

This is my location_location_relationships_form.html.erb where the collection_select is in:

<%= form_for(@location_location_relationship) do |f| %>  <% if @location_location_relationship.errors.any? %>  <div id="error_explanation">  <h2><%= pluralize(@location_location_relationship.errors.count, "error") %> prohibited this location_location_relationship from being saved:</h2>      <ul>    <% @location_location_relationship.errors.full_messages.each do |message| %>      <li><%= message %></li>    <% end %>    </ul>  </div>  <% end %>    <div class="field">    <%= f.label 'Von Ort' %><br />    <%= f.collection_select :predecessor_id, Location.all, :id, :name %>  </div>    <div class="field">    <%= f.label 'Zu Ort' %><br />    <%= f.collection_select :successor_id, Location.all, :id, :name %>  </div>  <div class="field">  <%= f.label 'Tour' %><br>  <%= f.collection_select :tour, Tour.all, :id, :name_of_tour, prompt: true %>  </div>  <div class="field">  <%= f.label 'Distanz' %><br>  <%= f.text_field :distance, type: "number", min:0 %>  </div>    <div class="actions">  <%= f.submit %>  </div>  <% end %>  

My model of the location_location_relationships:

class LocationLocationRelationship < ActiveRecord::Base  belongs_to :successor, class_name: "Location"  belongs_to :predecessor, class_name: "Location"  validates :successor_id, presence: true  validates :predecessor_id, presence: true    belongs_to :tour    validates :tour, presence: true  validates :distance, :numericality => true  #  validates :sequence, :numericality => {:only_integer => true}  #  validates :binary_variable, :numericality => {:only_integer => true}  end  

And my tours model:

class Tour < ActiveRecord::Base  #validates :tour, presence: true  has_many :location_location_relationships  def name_of_tour      name  end  end  

And the location_location_relationships controller:

class LocationLocationRelationshipsController < ApplicationController  before_action :set_location_location_relationship, only: [:show, :edit, :update, :destroy]      # GET /location_location_relationships  # GET /location_location_relationships.json  def index  @location_location_relationships = LocationLocationRelationship.all  end    # GET /location_location_relationships/1  # GET /location_location_relationships/1.json  def show  end    # GET /location_location_relationships/new  def new  @location_location_relationship = LocationLocationRelationship.new  end    # GET /location_location_relationships/1/edit  def edit  end    # POST /location_location_relationships  # POST /location_location_relationships.json  def create  @location_location_relationship = LocationLocationRelationship.new(location_location_relationship_params)    respond_to do |format|    if @location_location_relationship.save      format.html { redirect_to @location_location_relationship, notice: 'Die Distanz wurde angelegt.' }      format.json { render :show, status: :created, location: @location_location_relationship }    else      format.html { render :new }      format.json { render json: @location_location_relationship.errors, status: :unprocessable_entity }    end  end  end    # PATCH/PUT /location_location_relationships/1  # PATCH/PUT /location_location_relationships/1.json  def update  respond_to do |format|    if @location_location_relationship.update(location_location_relationship_params)      format.html { redirect_to @location_location_relationship, notice: 'Die Distanz wurde aktualisiert.' }      format.json { render :show, status: :ok, location: @location_location_relationship }    else      format.html { render :edit }      format.json { render json: @location_location_relationship.errors, status: :unprocessable_entity }    end  end  end    # DELETE /location_location_relationships/1  # DELETE /location_location_relationships/1.json  def destroy  @location_location_relationship.destroy  respond_to do |format|    format.html { redirect_to location_location_relationships_url, notice: 'Die Distanz wurde gelöscht.' }    format.json { head :no_content }  end  end  private  # Use callbacks to share common setup or constraints between actions.  def set_location_location_relationship    @location_location_relationship = LocationLocationRelationship.find(params[:id])  end    # Never trust parameters from the scary internet, only allow the white list through.  def location_location_relationship_params      params.require(:location_location_relationship).permit(:predecessor_id, :successor_id, :tour, :distance, :sequence, :binary_variable)  end  end  

rake test:prepare doesn't create test database

Posted: 26 Mar 2016 02:48 AM PDT

I'm on Rails 3.2.9 and when I try to run the following commands

rake db:drop db:create db:schema:load db:migrate test:prepare  rspec spec/  

The rspec commands throws an error

Mysql2::Error: Table 'app_test.articles' doesn't exist: SHOW FULL FIELDS FROM `articles` (ActiveRecord::StatementInvalid)  

But when I run the test:prepare command seperatly, it works:

rake db:drop db:create db:schema:load db:migrate  rake test:prepare  rspec spec/  

Why does preparing the test database in the same rake command not work?

How do I nest models using a form_tag in Rails 4?

Posted: 26 Mar 2016 01:30 AM PDT

I've got a form to add SaleQualifiers to my app - which works fine when I'm using:

<%= form_for(@sale_qualifier, :html => {role: :form, 'data-model' => 'sale_qualifier'}, remote: true) do |f| %>

The problem with form_for is that I want to put the form inline within a table row in my view - so as a method to get around that I'm now using:

<%= form_tag('/sale_qualifiers', method: :post, remote: true) do -%> <%= fields_for :sale_qualifier do |ff| %>

This is working fine for most of the fields I need to generate, but I've got a nested attribute field for Answer (Answer belongs_to SaleQualifier). This is not generating the right field names in the view, and as a result when I go to save the object this way I don't capture the answer_attributes.

Here's the full working form using form_for:

<div class="panel panel-default">   <%= form_for(@sale_qualifier, :html => {role: :form, 'data-model' => 'sale_qualifier'}, remote: true) do |f| %>    <% if @sale_qualifier.errors.any? %>    <div id="error_explanation">      <h2><%= pluralize(@sale_qualifier.errors.count, "error") %> prohibited this answer from being saved:</h2>      <ul>      <% @sale_qualifier.errors.full_messages.each do |message| %>        <li><%= message %></li>      <% end %>      </ul>    </div>  <% end %>  <div class="panel-body">    <div class="col-sm-6">      <h2><%= @question.question_text %></h2>      <% unless @question.id == 1 %>        <p><%= link_to('Back', edit_sale_qualifier_path(id: @prior_sale_qualifier), data: { disable_with: "Loading..." }, :remote => true) %></p>      <% end %>    </div>    <div class="col-sm-6">      <div class="form-group">        <%= f.hidden_field :sales_opportunity_id, :value => @sales_opportunity.id %>      </div>      <div class="form-group">        <%= f.hidden_field :question_id, :value => @question.id %>      </div>      <% unless @question.id == 1 %>        <div class="form-group">          <%= f.hidden_field :prior_question_id, :value => @prior_question_id %>        </div>      <% end %>      <%= f.fields_for :answer do |answer| %>      <div class="form-group">        <% if @question.answer_type == 'Text Field' %>          <%= answer.text_area :answer_text, :placeholder => "Enter your answer", :class => "form-control"%>        <% end %>        <% if @question.answer_type == 'Datetime' %>          <div class='input-group date' id='datetimepicker' data-date-format="YY.MM.DD">            <%= answer.text_field :answer_text, class: "form-control", data: { date_format: 'YYYY/MM/DD' }, :placeholder => "YYYY/MM/DD" %>            <span class="input-group-addon">              <span class="glyphicon glyphicon-calendar"></span>             </span>          </div>        <% end %>        <% if @question.answer_type == 'Boolean' %>          <%= answer.select :answer_text, [['Yes', true], ['No', false]] %>        <% end %>        <% if @question.answer_type == 'Update' || @question.answer_type == 'Result' %>          <%= answer.hidden_field :answer_text, :value => "Updated" %>        <% end %>        <span class="warning-block"></span>        <span class="help-block"></span>      </div>      <% end %>        <% if @question.answer_type == 'Update' || @question.answer_type == 'Result' %>          <div class="actions">            <%= f.submit "Done", class: "btn btn-large btn-success", data: { disable_with: "Submitting..." }, autocomplete: 'off' %>          </div>        <% else %>          <div class="actions">            <%= f.submit "Submit", class: "btn btn-large btn-success", data: { disable_with: "Submitting..." }, autocomplete: 'off' %>          </div>        <% end %>      <% end %>    </div>   </div>  </div>  

Here's the code which does not work using form_tag:

<%= form_tag('/sale_qualifiers', method: :post, remote: true) do -%>   <%= fields_for :sale_qualifier do |ff| %>    <%= ff.hidden_field :sales_opportunity_id, :value => @sales_opportunity.id %>    <%= ff.hidden_field :question_id, :value => @question.id %>     <tr>      <td><%= @question.question_text %></td>      <td>          <%= ff.fields_for :answer do |answer| %>          <% if @question.answer_type == 'Text Field' %>            <%= answer.text_area :answer_text%>          <% end %>          <% if @question.answer_type == 'Datetime' %>              <div class='input-group date' id='datetimepicker' data-date-format="YY.MM.DD">              <%= answer.text_field :answer_text, class: "form-control", data: { date_format: 'YYYY/MM/DD' }, :placeholder => "YYYY/MM/DD" %>              <span class="input-group-addon">               <span class="glyphicon glyphicon-calendar"></span>              </span>               </div>          <% end %>          <% if @question.answer_type == 'Boolean' %>            <%= answer.select :answer_text, [['Yes', true], ['No', false]] %>          <% end %>          <% end %>          </td>          <td>              <%= ff.submit "Submit", class: "btn btn-large btn-success", data: { disable_with: "Submitting..." }, autocomplete: 'off' %>          </td>      </tr>  <% end %>       <% end %>    

For completeness, the issue I'm having is that the generated html for the working code creates the following field:

textarea id="sale_qualifier_answer_attributes_answer_text" name="sale_qualifier[answer_attributes][answer_text]"  

The broken code creates the following html:

Textarea id="sale_qualifier_answer_answer_text" name="sale_qualifier[answer][answer_text]"  

So how can I get the html output to show "sale_qualifier[answer_attributes][answer_text]" rather than "sale_qualifier[answer][answer_text]" in this instance using form_tag?

Rails 4 + Capistrano + AWS Net::SSH::AuthenticationFailed: deploy

Posted: 26 Mar 2016 03:34 AM PDT

I followed this tutorial to deploy my Rails 4 app using capistrano to AWS and having a hard time solving this issue.

When I run cap production deploy, it fails with the below error

Net::SSH::AuthenticationFailed: deploy  

Below is the is full trace

** Invoke production (first_time)  ** Execute production  ** Invoke load:defaults (first_time)  ** Execute load:defaults  ** Invoke bundler:map_bins (first_time)  ** Execute bundler:map_bins  ** Invoke rvm:hook (first_time)  ** Execute rvm:hook  ** Invoke rvm:check (first_time)  ** Execute rvm:check  DEBUG [2439e1e0] Running ~/.rvm/bin/rvm version on 52.37.242.197  DEBUG [2439e1e0] Command: ~/.rvm/bin/rvm version  cap aborted!  Net::SSH::AuthenticationFailed: deploy  /home/pavan/.rvm/gems/ruby-2.2.3/gems/net-ssh-2.7.0/lib/net/ssh.rb:215:in `start'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/backends/connection_pool.rb:25:in `create_or_reuse_connection'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/backends/netssh.rb:173:in `ssh'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/backends/netssh.rb:126:in `block in _execute'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/backends/netssh.rb:123:in `tap'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/backends/netssh.rb:123:in `_execute'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/backends/netssh.rb:76:in `capture'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/capistrano-rvm-0.1.2/lib/capistrano/tasks/rvm.rake:9:in `block (3 levels) in <top (required)>'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/backends/netssh.rb:54:in `instance_exec'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/backends/netssh.rb:54:in `run'  /home/pavan/.rvm/gems/ruby-2.2.3/gems/sshkit-1.3.0/lib/sshkit/runners/parallel.rb:12:in `block (2 levels) in execute'  Tasks: TOP => rvm:check  

According to this SO post I tried locking net-ssh at 2.7.0 and net-ssh-gateway at 1.2.0 but the error still persists. Any help is appreciated.

Environment:

OS - Ubuntu 14.04 LTS

Ruby - 2.2.3p173

Rails - 4.2.5

Capistrano - 3.4.0

net-ssh - 2.7.0

net-ssh-gateway - 1.2.0

Rails, check condition when user click button_to

Posted: 26 Mar 2016 06:21 AM PDT

I'm doing an application for booking movie. For each movie have a "book" button, normally it just direct to another page handled by a controller. But is there any way to do like this? if user not login before, show a popup to redirect to login page, else direct to booking controller?

Current in my movie controller is:

<td><%= button_to "Book", {:controller => "booking",:action=>"new", :movie_session_id => movie.id}, :method => :post %></td>  

is it possible if I check condition in this page or I have to check in BookingController?

Small preview when sharing link on Social media Ruby On Rails

Posted: 26 Mar 2016 12:10 AM PDT

I'm working on a site whose front end is in angularjs and backend in ROR , Same ROR API is used in an android app also . Now I have a situation here . I need to share my Web's post on the Social media like facebook , twitter and google plus . And along with the link to the single post there should be a small preview also (a preview of the post which crawls before posting e.g in facebook) .I did it using angular Plugins . But when it comes to Android side , what they share and what displays on Facebook is the Link only . Then i did some R&D and i came to know that it must be done on server side with social media meta tags . I did a little bit but it still no works . I'm stuck on it . Below is what i've done so far .

 def show    @post = Post.find_by_permalink(params[:id])      respond_to do |format|          format.html      end  end  

In My views posts/show.html.erb

<!DOCTYPE html>  <html>  <head>      <title> Shared Question</title>        <meta property="og:title" content="My Page" />      <meta property="og:description" content="A description of my page." />      <meta property="og:image" content="http://www.example.com/images/my_lovely_face.jpg" />      <!-- etc. -->  </head>  <body>  Here is the body  </body>  </html>  

And when i click on link , share on e.g facebook . it gives me

406 Not Acceptable

. I know it is due to rendering format but don't know how to get rid of it .

I just need to show a small preview whenever some user share my web post's link on any media

undefined method `symbolize_keys' for "myparamsimtryingtopass":String

Posted: 26 Mar 2016 12:55 AM PDT

So im still very new to ruby on rails and what Im trying to do here is very simple. Im trying to create a facebook like app where if you click on the profile picture of a post it will direct you to the users profile page. I have just done something really similar in a online course but I cant seem to get this one to work in another view. Here is what I have that works in my header, navbar.

NAVBAR

<nav class="navbar navbar-default navbar-fixed-top">    ......    <li><%= link_to "Show Profile" ,             user_profile_path(current_user.id, current_user.full_name) %></li>     ....  </nav>  

This code works and directs me to the corresponding users profile page.

Routes

Rails.application.routes.draw do    ....    root 'statuses#index'      get '/:id/:full_name', to: 'profile#show' , as: :user_profile    .....  end  

Problem View

<div class="page-header">  ....  <% @statuses.each do |status| %>      <div class="row">        <div class="col-md-1">          <%= link_to image_tag(status.user.avatar.url(:thumb),              user_profile_path(status.user.id, status.user.full_name)) %>          //the above is what gives me the error in the title.        </div>  <% end %>  

I have done my fair share of searching around and it seems that this error occurs if im passing in strings when it accepts hashkeys? Im not entirely sure. If there is a better way to do this that I should use please show me as I am very new and open to learning.

Rails: Unable to sign_in a user using Devise

Posted: 26 Mar 2016 12:45 AM PDT

I created a demo authentication application in rails using Devise gem. I created a sessions controller to sign in a user. But when I'm sending a request localhost:3000/api/v1/sessions/ using postman to the session controller I'm getting the following error :

"Could not find a valid mapping for #<User id: 2, email: "smith@railsapi.com", encrypted_password: "$2a$10$J5lCfQzWsxvjsXe.3EXfZ.ST9nztLLW8fhqYgXNtJP1...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: "2016-03-26 03:59:22", updated_at: "2016-03-26 03:59:22", auth_token: "_D3GU1TftgP7YHNcRftN">"  

Here's my model users.rb

class User < ActiveRecord::Base         before_create :generate_authentication_token!      devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable    validates :auth_token, uniqueness: true      def generate_authentication_token!      begin        self.auth_token = Devise.friendly_token      end while self.class.exists?(auth_token: auth_token)    end  end  

Here's my sessions controller

class Api::V1::SessionsController < ApplicationController      def create      user_password = params[:session][:password]      user_email = params[:session][:email]      puts user_password      puts user_email      user = user_email.present? && User.find_by(email: user_email)        if user.valid_password? user_password        sign_in user, store: false        user.generate_authentication_token!        user.save        render json: user, status: 200      else        render json: { errors: "Invalid email or password" }, status: 422      end    end  end  

And My routes.rb file :

Rails.application.routes.draw do    # API routes path    namespace :api, defaults: { format: :json } do      namespace :v1 do        resources :users, only: [:show, :create, :update]        resources :sessions, only:[:create, :destroy]      end    end    end   

Application.rb

require File.expand_path('../boot', __FILE__)    require 'rails/all'    # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)    module DemoApi    class Application < Rails::Application      # Settings in config/environments/* take precedence over those specified here.      # Application configuration should go into files in config/initializers      # -- all .rb files in that directory are automatically loaded.        # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.      # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.      # config.time_zone = 'Central Time (US & Canada)'        # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.      # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      # config.i18n.default_locale = :de        # Do not swallow errors in after_commit/after_rollback callbacks.      config.active_record.raise_in_transactional_callbacks = true        DeviseController.respond_to :html, :json    end  end  

I would really appreciate if someone can tell me where I'm going wrong. Thanks

Adding year for all records with update_all

Posted: 26 Mar 2016 02:08 AM PDT

I need to update all records in my model by adding another year before the date saved , seek information and an option is with update_all , I really would help an example with dates update_all database: PostgreSQL

An example: the saved date is this 15/01/16 after executing the action 01/15/17 and so on all records.

or some other option would be very helpful!

When use redis for kvs, Which is speedy to use 1 db or different ones

Posted: 26 Mar 2016 05:44 AM PDT

I'm a developper using rails application to use redis.

I'm making some functions using redis by ruby now.

so, I have a quastion which is speedy to use redis 1db or multiple ones. for example, I make a follow 2 functions with 2 gems.

  • histories_function: using redis-objects
  • counts_function: using sidekiq

Which connection is better??

to connect same db

Redis::Objects.redis = Redis.new (host: '127.0.0.1', port: 6379, db: 0)  Sidekiq.redis = Redis.new(host: '127.0.0.1', port: 6379, db: 0)  

or

to connect different db

Redis::Objects.redis = Redis.new (host: '127.0.0.1', port: 6379, db: 0)  Sidekiq.redis = Redis.new(host: '127.0.0.1', port: 6379, db: 1)  

if you like ,please tell me the reasons with answer. Thanks.

How to display image in email using action mailer in ruby on rails

Posted: 26 Mar 2016 07:02 AM PDT

I am making a application for sending mail to users, for that I am using action mailer in my application.
I want show a image in mail but I am not able to do this.Can anyone help in how to make it possible. I am using paper clip gem for storing images in my application. Field in database storing image name like
prescription_file_name => "foo_bar_thumbnail_image7.jpg" but the actually complete URL for that image is like

"/system/service_requests/prescriptions/000/000/237/medium/foo_bar_thumbnail_image7.jpg?1455861395".  

Thanks in advance

rails : type search with data address use elasticsearch chewy gem

Posted: 25 Mar 2016 11:00 PM PDT

I use chewy gem elasticsearch .

I have LocationsIndex, mapping :

class LocationsIndex < Chewy::Index    settings analysis: {      analyzer: {        folding: {            tokenizer: "standard",            filter:  [ "lowercase", "asciifolding" ]          },        sorted: {          tokenizer: 'keyword',          filter: ['lowercase', 'asciifolding']        }      }    }      define_type Location do      field :name, type: 'string', analyzer: 'standard' do        field :folded, type: 'string', analyzer:   "folding"      end      field :address, type: 'string', analyzer: 'standard' do        field :address, type: 'string', analyzer: 'folding'      end      field :locations, type: 'geo_point', value: ->{ {lat: lat, lon: lon} }    end    end  

when i query:

LocationsIndex::Location.query(          multi_match: {            query: keyword,            fields: ["address", "address.folded" ,"name", "name.folded"]          }        )  

data sample :

{ "took" : 2, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "failed" : 0 }, "hits" : { "total" : 10, "max_score" : 1.0, "hits" : [ { "_index" : "locations", "_type" : "location", "_id" : "131", "_score" : 1.0, "_source":{"name":"Việt Nam","address":"Việt Nam","locations":{"lat":16.9054,"lon":106.576}} }, { "_index" : "locations", "_type" : "location", "_id" : "136", "_score" : 1.0, "_source":{"name":"Quan truong Ngo Mon","address":"23/8, Thừa Thiên Huế, Việt Nam","locations":{"lat":16.4669,"lon":107.58}} }, { "_index" : "locations", "_type" : "location", "_id" : "132", "_score" : 1.0, "_source":{"name":"Thừa Thiên Huế","address":"Thừa Thiên Huế, Việt Nam","locations":{"lat":16.4674,"lon":107.591}} }, { "_index" : "locations", "_type" : "location", "_id" : "137", "_score" : 1.0, "_source":{"name":"Phu Van Lau","address":"23/8, Thừa Thiên Huế, Việt Nam","locations":{"lat":16.4655,"lon":107.581}} }, { "_index" : "locations", "_type" : "location", "_id" : "133", "_score" : 1.0, "_source":{"name":"Ha Noi","address":"Ha Noi, Việt Nam","locations":{"lat":16.4674,"lon":107.591}} }, { "_index" : "locations", "_type" : "location", "_id" : "138", "_score" : 1.0, "_source":{"name":"Cau gia Vien","address":"Le Duan, Thừa Thiên Huế, Việt Nam","locations":{"lat":16.4601,"lon":107.571}} }, { "_index" : "locations", "_type" : "location", "_id" : "134", "_score" : 1.0, "_source":{"name":"TP Ho Chi Minh","address":"TP Ho Chi Minh, Việt Nam","locations":{"lat":16.4674,"lon":107.591}} }, { "_index" : "locations", "_type" : "location", "_id" : "139", "_score" : 1.0, "_source":{"name":"Chua thien Pagoda","address":"Kim Long, Thừa Thiên Huế, Việt Nam","locations":{"lat":16.4537,"lon":107.545}} }, { "_index" : "locations", "_type" : "location", "_id" : "130", "_score" : 1.0, "_source":{"name":"Việt Nam","address":"Việt Nam","locations":{"lat":16.9054,"lon":106.576}} }, { "_index" : "locations", "_type" : "location", "_id" : "135", "_score" : 1.0, "_source":{"name":"Dai Noi Hue","address":"23/8, Thừa Thiên Huế, Việt Nam","locations":{"lat":16.4698,"lon":107.577}} } ] } }

when i run query with keyword = "viet nam"

result :   _id = [131,132,,133,134,135,136,137,138,139,130]  # => OK working  

but i when run query with keywork = "thua thien hue"

result :       _id = [132,135,139]  # => Don't working ???, should have been: _id = [132,135,136,137,138,139]  

Same with keywork = "hue"

result :           _id = [132,135]  # => Don't working ???, should have been: _id = [132,135,136,137,138,139]  

how search results that contain the above word (add type, or do anything)

Globalize 3 gem sorting array with translation::

Posted: 25 Mar 2016 10:53 PM PDT

What I want to achieve: dynamically create category sorter using isotope.js from my Gallery.tag

To do that I need to

  1. loop out a lowercase unique tags for my html .class
  2. loop out the tag (using globalize 3 for translation) to display in the <h2>

I cannot use @galleries for both cases because upon switch language it will output chinese character to my .class which breaks the sorter. Therefore I created two arrays and combine them together with zip and the looping it with each.

I try to sort them by alphabetic order, but my corresponding Chinese tags are not following my English order.

galleries/index.html.erb

<% @uniq_test = [] %>      <% @galleries_order.each do |gallery| %>          <% next if @uniq_test.include?(gallery.tag) %>      <% @uniq_test << gallery.tag %>  <% end %>  <% @sorters = @sorters.map(&:downcase).sort! %>  <% @uniq_test = @uniq_test.map(&:downcase).sort! %>  <% @uniq_sorters = @uniq_test.zip(@sorters) %>  <div class="main">      <div class="gallery-select-wrapper">          <div class="sort-gallery-buttons animated slideInLeft text-center">              <h2 id="recent"class="recent"><%= t"galleries.sorter.recent"%></h2>      <% @uniq_sorters.each do |uniq, sorter| %>          <% if sorter != nil %>              <% str = "<h2 class='" + sorter + "'" + "id='"+ sorter + "'>"%>              <%= str.html_safe + uniq + "</h2>".html_safe %>          <% end %>      <% end %>          </div>      </div>  </div>  

controllers/galleries.rb

def index      @galleries = Gallery.all.order("created_at DESC")      @galleries_order = Gallery.all.order("title ASC")      @sorters = Gallery.uniq.pluck(:tag)      gon.tags = Gallery.uniq.pluck(:tag)  end  

en categories are [country, theme, project, war] zh categories are [主題,國家, 戰爭, 項目] <-- current (in en = theme, country, war, project) my categories are [國家, 主題, 項目, 戰爭] <-- goal (same as en)

in a nutshell I want chinese translation to follow my english alphabetic order.

enter image description here

enter image description here

How do I handle Group Membership Join Requests in Rails?

Posted: 26 Mar 2016 12:16 AM PDT

I have groups that are created by users and have one user-owner. Groups have many members. I want to make it so users have to request to join a group. I have a has_many through model for memberships and a has_many through model for requests. This easily appears to be the best method due to the CRUD actions used in the request system (sending new requests, deleting/updating requests, etc.). However, I am having a ton of issues with routing, with controller actions, and with model connections.

Numerous different errors are showing up with each thing I try so I won't post the errors and ask for individual fixes here; that would take forever.

My questions are:

  • Do my models look correct? Am I using the join model and model references correctly?
  • How do I need to set up my controller actions in order to capture the request system I'm trying to implement? How do I set up sending(creating), updating(accepting), and destroying(ignoring)?
  • How do I need to set up my routes? Nested or not? How do I set up the request create path? (I'm having issues with this a lot in particular; I'm frequently getting the error: "No route matches [POST] /cliqs/cliq_requests" or "Couldn't find Cliq with 'id'=")

Simply what am I doing wrong? What are the best practices I can use?

For clarity:

  • Groups = Cliqs

Here are my models:

User Model:

class User < ActiveRecord::Base  has_many :uploads  has_one :owned_cliq, foreign_key: 'owner_id', class_name: 'Cliq', dependent: :destroy    has_many :cliq_memberships, dependent: :destroy  has_many :cliqs, through: :cliq_memberships    has_many :cliq_requests, through: :cliq_requests  has_many :sent_cliq_requests, foreign_key: 'cliq_request_recipient_id', class_name: 'CliqRequest', dependent: :destroy  end  

Group Request Model:

class CliqRequest < ActiveRecord::Base  #from  belongs_to :cliq_request_sender, class_name: 'User', foreign_key: 'cliq_request_sender_id'  #to  belongs_to :cliq_request_recipient, class_name: 'Cliq', foreign_key: 'cliq_request_recipient_id'  end  

Group Membership Model:

class CliqMembership < ActiveRecord::Base  belongs_to :cliq  belongs_to :user  end  

Group Model:

class Cliq < ActiveRecord::Base  belongs_to :owner, class_name: 'User'    has_many :cliq_memberships, dependent: :destroy  has_many :members, through: :cliq_memberships, source: :user    has_many :cliq_requests, through: :cliq_requests  has_many :cliq_requests_from_sender, foreign_key: 'cliq_request_sender_id', class_name: 'CliqRequest', dependent: :destroy  end  

My controllers: User and Membership Controllers work fine and seem arbitrary to this problem.

Group Request Controller:

class CliqRequestsController < ApplicationController  before_action :set_cliq_request, except: [:index, :create]  before_action :check_if_owner, except: [:create]    def create      @cliq_request_sender = User.find(current_user)      @cliq_request_recipient = Cliq.find(params[:id])      @cliq_request = current_user.cliq_requests.new(cliq_request_sender: cliq_request_sender)        if @cliq_request.save          #render changed cliq_request badge          redirect_to current_user      else          #render errors          redirect_to cliq_path      end   end    def update      @cliq_request.accept  end    def index      @incoming = CliqRequest.where(cliq_request_sender: cliq_request_sender)      @outgoing = current_user.cliq_requests  end    def destroy      @cliq_request.destroy  end    private  def check_if_owner      if current_user != @cliq.owner      redirect_to current_user      end   end  end  

Group Controller:

class CliqsController < ApplicationController    def index      @cliqs = Cliq.all  end    def show      @cliq = Cliq.find(params[:id])      @cliq_owner = @cliq.owner      @cliq_members = @cliq.members  end    def new      @cliq = Cliq.new(params[:id])  end    def create      @cliq = current_user.build_owned_cliq(cliq_params)      @cliq.members << current_user        if @cliq.save          redirect_to current_user      else          redirect_to new_cliq_path      end  end    def destroy  end      def cliq_params      params.require(:cliq).permit(:name, :cliq_id)  end  end  

Here are my routes:

Rails.application.routes.draw do  get '/home/index'    root 'home#index'    devise_for :admins    devise_for :users    resources :users, :only => [:show]    resources :uploads    get '/index' => 'uploads#index'    resources :cliqs do    resources :cliq_requests  end    resources :cliq_memberships  

The create request route:

<%= link_to 'Request to join Cliq', '/cliqs/:cliq_id/cliq_requests', :method => :post %>  

How to efficiently mass update in Rails?

Posted: 25 Mar 2016 11:01 PM PDT

I'm working on an integration with our warehouse. We receive an XML message with all our SKUs and their inventory levels. For each SKU I need to update the inventory level in my rails app. However, every time I request the XML message, the processing is very slow, to the point where the browser times out. I suspect this is because I have to do a look up for each SKU by name and update the inventory level for it. There should be around 1000 SKUs returned in the XML, this means 2 lookups for each SKU and 1 save.

Is there a way for me to optimize the performance for this integration? I am fairly new to Rails but I feel like there should be a more efficient way of doing this.

Example XML:

<InventoryXML>  <Item>     <ItemID>ABC-12-2345</ItemID>     <ItemQty>14</ItemQty>     <Warehouses>      <Warehouse>         <Name>Constitution</Name>        <Quantity>9</Quantity>       </Warehouse>      <Warehouse>         <Name>Vegas</Name>        <Quantity>1</Quantity>       </Warehouse>      <Warehouse>         <Name>Atlanta</Name>        <Quantity>4</Quantity>       </Warehouse>    </Warehouses>   </Item>  </InventoryXML>  

Code:

def process_inventory      @doc.xpath('//Item').each do |item|          name = item.xpath('//ItemID').text          warehouses = item.xpath('//Warehouses')          warehouses.xpath('Warehouse').each do |warehouse|              if warehouse.xpath('Name').text == "Vegas"                  self.update_inventory_for_sku(2, name, warehouse.xpath('Quantity').text.to_i)              elsif warehouse.xpath('Name').text == "PA"                  self.update_inventory_for_sku(1, name, warehouse.xpath('Quantity').text.to_i)              end          end      end      return "Succesfully updated SKU inventory"  end    def update_inventory_for_sku(vendor_id, name, quantity)      sku = VendorSku.where({vendor_id: vendor_id, name: name}).first      if sku          sku.update_attributes(inventory_quantity: quantity)      else          self.hub_error_message += "\nSKU not found: " + name.to_s + "for vendor_id: " + vendor_id.to_s      end  end  

How to get values from referenced table Rails

Posted: 25 Mar 2016 09:03 PM PDT

I have 3 models with the following structure:

Application and Photo belongs_to Listing. Listing has_many photos and applications.

    class Listing < ActiveRecord::Base        belongs_to :user        has_many :photos        has_many :applications      end        class Application < ActiveRecord::Base        belongs_to :user        belongs_to :listing      end        class Photo < ActiveRecord::Base         belongs_to :listing      end  

I'm trying to get the photos of the listings that are associated with a users applications.

I start in the controller by passing all the applications of the current user:

    @apps = current_user.applications  

In the view I want to display all the photos like this:

     <% @apps.each do |app| %>          <%= image_tag app.listing.photos[0].image.url(:thumb) if app.listing.photos.length > 0 %>       <% end %>  

But I get this error when trying to render the view:

undefined method `photos' for nil:NilClass

Can't I access the photo that belongs to the listing that belongs to the application with this syntax - app.listing.photos[0].image.url ?

Rails - UndefinedMethod in model#new action

Posted: 25 Mar 2016 09:45 PM PDT

My routes.rb looks as such:

resources :users do   resources :reservations do    resources :orders   end  end    resources :reservations do   resources :orders   end   

Models:

class User < ActiveRecord::Base    has_many :reservations    has_many :orders, :through => :reservations  end    class Reservation < ActiveRecord::Base    has_one :order    belongs_to :user  end    class Order < ActiveRecord::Base    belongs_to :reservation  end  

Controllers:

class ReservationsController < ApplicationController      def new     if current_user      @user         = User.find_by_id(current_user)      @reservation  = @user.reservations.build     else      @reservation  = Reservation.new     end    end      #leaving out the save portion to make question shorter.     def create     if current_user      @user         = User.find(current_user)      @reservation  = @user.reservations.create(reservation_params)     else      @reservation  = Reservation.new(reservation_params)     end    end   end    class OrdersController < ApplicationController      def new     if current_user      @user         = User.find_by_id(current_user)      @order        = @user.build_order     else      @reservation  = Reservation.find_by_id(params[:reservation_id])      @order        = @reservation.build_order     end    end      def create     if current_user      @user         = User.where(current_user)      @order        = @user.orders.create(order_params)     else      @reservation  = Reservation.find(params[:reservation_id])      @order        = @reservation.create_order(order_params)     end    end  end  

Error

NoMethodError in OrdersController#new

undefined method `build_order' for #

Full stack trace is as such:

activemodel (4.2.5) lib/active_model/attribute_methods.rb:433:in                     `method_missing'  app/controllers/orders_controller.rb:29:in `new'  actionpack (4.2.5)     lib/action_controller/metal/implicit_render.rb:4:in `send_action'  actionpack (4.2.5) lib/abstract_controller/base.rb:198:in `    process_action'  actionpack (4.2.5) lib/action_controller/metal/rendering.rb:10:in `process_action'  actionpack (4.2.5) lib/abstract_controller/callbacks.rb:20:in `block in process_action'  activesupport (4.2.5) lib/active_support/callbacks.rb:117:in `call'  activesupport (4.2.5) lib/active_support/callbacks.rb:117:in `call'  activesupport (4.2.5) lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'  activesupport (4.2.5) lib/active_support/callbacks.rb:505:in `call'  activesupport (4.2.5) lib/active_support/callbacks.rb:505:in `call'  activesupport (4.2.5) lib/active_support/callbacks.rb:92:in     `__run_callbacks__'  activesupport (4.2.5) lib/active_support/callbacks.rb:778:in     `_run_process_action_callbacks'  activesupport (4.2.5) lib/active_support/callbacks.rb:81:in `run_callbacks'  actionpack (4.2.5) lib/abstract_controller/callbacks.rb:19:in `process_action'  actionpack (4.2.5) lib/action_controller/metal/rescue.rb:29:in `process_action'  actionpack (4.2.5)     lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'  activesupport (4.2.5) lib/active_support/notifications.rb:164:in `block in instrument'  activesupport (4.2.5) lib/active_support/notifications/instrumenter.rb:20:in `instrument'  activesupport (4.2.5) lib/active_support/notifications.rb:164:in `instrument'  actionpack (4.2.5) lib/action_controller/metal/instrumentation.rb:30:in `process_action'  actionpack (4.2.5) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'  activerecord (4.2.5) lib/active_record/railties/controller_runtime.rb:18:in `process_action'  actionpack (4.2.5) lib/abstract_controller/base.rb:137:in `process'  actionview (4.2.5) lib/action_view/rendering.rb:30:in `process'  actionpack (4.2.5) lib/action_controller/metal.rb:196:in `dispatch'  actionpack (4.2.5) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'  actionpack (4.2.5) lib/action_controller/metal.rb:237:in `block in action'  actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:76:in `call'  actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:76:in `dispatch'  actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:45:in `serve'  actionpack (4.2.5) lib/action_dispatch/journey/router.rb:43:in `block in serve'  actionpack (4.2.5) lib/action_dispatch/journey/router.rb:30:in `each'  actionpack (4.2.5) lib/action_dispatch/journey/router.rb:30:in `serve'  actionpack (4.2.5) lib/action_dispatch/routing/route_set.rb:817:in `call'  rack (1.6.4) lib/rack/etag.rb:24:in `call'  rack (1.6.4) lib/rack/conditionalget.rb:25:in `call'  rack (1.6.4) lib/rack/head.rb:13:in `call'  actionpack (4.2.5) lib/action_dispatch/middleware/params_parser.rb:27:in `call'  actionpack (4.2.5) lib/action_dispatch/middleware/flash.rb:260:in `call'  rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'  rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'  actionpack (4.2.5) lib/action_dispatch/middleware/cookies.rb:560:in `call'  activerecord (4.2.5) lib/active_record/query_cache.rb:36:in `call'  activerecord (4.2.5) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'  activerecord (4.2.5) lib/active_record/migration.rb:377:in `call'  actionpack (4.2.5) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'  activesupport (4.2.5) lib/active_support/callbacks.rb:88:in     `__run_callbacks__'  activesupport (4.2.5) lib/active_support/callbacks.rb:778:in     `_run_call_callbacks'  activesupport (4.2.5) lib/active_support/callbacks.rb:81:in     `run_callbacks'  actionpack (4.2.5) lib/action_dispatch/middleware/callbacks.rb:27:in `call'  actionpack (4.2.5) lib/action_dispatch/middleware/reloader.rb:73:in `call'  actionpack (4.2.5) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'  actionpack (4.2.5)             lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'  web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'  web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch'  web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'  actionpack (4.2.5)     lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'  railties (4.2.5) lib/rails/rack/logger.rb:38:in `call_app'  railties (4.2.5) lib/rails/rack/logger.rb:20:in `block in call'  activesupport (4.2.5) lib/active_support/tagged_logging.rb:68:in `block in tagged'  activesupport (4.2.5) lib/active_support/tagged_logging.rb:26:in `tagged'  activesupport (4.2.5) lib/active_support/tagged_logging.rb:68:in `tagged'  railties (4.2.5) lib/rails/rack/logger.rb:20:in `call'  actionpack (4.2.5) lib/action_dispatch/middleware/request_id.rb:21:in `call'  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'  rack (1.6.4) lib/rack/runtime.rb:18:in `call'  activesupport (4.2.5)     lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'  rack (1.6.4) lib/rack/lock.rb:17:in `call'  actionpack (4.2.5) lib/action_dispatch/middleware/static.rb:116:in `call'  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'  railties (4.2.5) lib/rails/engine.rb:518:in `call'  railties (4.2.5) lib/rails/application.rb:165:in `call'  rack (1.6.4) lib/rack/content_length.rb:15:in `call'  puma (3.1.0) lib/puma/configuration.rb:227:in `call'  puma (3.1.0) lib/puma/server.rb:561:in `handle_request'  puma (3.1.0) lib/puma/server.rb:406:in `process_client'  puma (3.1.0) lib/puma/server.rb:271:in `block in run'  puma (3.1.0) lib/puma/thread_pool.rb:111:in `call'  puma (3.1.0) lib/puma/thread_pool.rb:111:in `block in spawn_thread'  

I'm able to make a reservation and order when there is no 'current_user' but where I'm running into an issue is when a user is signed-in I'm able to make a reservation and it saves to the DB but then I get a no method error in the Orders#new controller @order = @user.build_order line. I have tried a lot of variations such as @user.order.new, @user.order.build

I've also tried @order = @user.reservations.order(params[:reservation_id]) but this leads me to a 'to_key' issue for the orders _form.

None of the options I've mentioned work nor more options that I have tried which I don't remember anymore. I would greatly appreciate help.

Please let me know if more information is needed from me, I will try to post it soon as possible.

price range filter using elastisearch-rails

Posted: 25 Mar 2016 07:48 PM PDT

I'm trying to create a price range filter like the one in the image here or something like the spree_elasticsearch gem

I'm new to ruby on rails can someone please help me out simple code for form view and search method

say I have the following models

class Product < ActiveRecord::Base    belongs_to :category    include Searchable  end    class Category < ActiveRecord::Base    has_many :products  end  

and haml views

= form_tag search_path, method: 'get', role: 'search' do = text_field_tag :q, params[:q], class: 'form-control', placeholder: 'Search...'

I'm only interested in price range and checkboxes for filtering categories

1 comment:

  1. It is nice blog Thank you porovide important information and i am searching for same information to save my time Ruby on Rails Online Training India

    ReplyDelete