Posts

Showing posts with the label ruby-on-rails

Minitest - calling a mocked instance method from within another instance method

Minitest - calling a mocked instance method from within another instance method I've come across some weird behavior in Minitest::Mock and can't figure out what's the reason behind it. Minitest::Mock Say I have this class A that has a method b that calls method c : b c class A def b c end def c 1 end end I would like to mock the c method to return 2 instead of 1: c require 'minitest/autorun' a = Minitest::Mock.new(A.new) a.expect(:c, 2) But for some reason b still returns 1: b > a.b => 1 Obviously calling c directly will work: c > a.c => 2 > a.c MockExpectationError: No more expects available for :c: Why is the expectation on c not being invoked when calling it from within the instance? c 1 Answer 1 This is how Minitest::Mock works; the mock object is a wrapper around the "real" instance of A , and defined expectations intercept the...

Optimize with joins, order, distinct on current active records / sql query

Optimize with joins, order, distinct on current active records / sql query I am using ruby on rails 4 and postgres currently, and making distinct and sorting as in the code below. I just have a feeling is not right and not optimized because it seems to be doing all this with an array. How could I combine this all into one activerecords query ? ads1 = Advertisement.where(property_id: nil) .where(target_address_city: [property.address_city, ""], target_address_state: [property.address_state, ""], target_address_country_id: property.address_country_id) # return advertisement belongs to the property ads2 = management.property.advertisements #combine both results combine_ads = ads1 + ads2 #remove ads duplicate uniq_ads = combine_ads.uniq { |ads| ads.id} # sort by created_at desc uniq_ads = uniq_ads.sort_by { |ads| -ads[:id]} # do pagination final_ads = uniq_ads.paginate(:page => pa...

RAILS How can I build a nested form to change a has_many through associated object boolean attribute using checkboxes?

RAILS How can I build a nested form to change a has_many through associated object boolean attribute using checkboxes? I have 3 Models: User , Profile and Photo . User Profile Photo Profile < ApplicationRecord belongs_to :user has_many :photos, through: :user Photo < ApplicationRecord belongs to :user User < ApplicationRecord has_one :profile has_many :photos I'd like to build a form for @profile that also displays checkboxes for all of its associated photos. @profile When a photo is checked, I'd like the that photo's # featured_status to be turned to be TRUE . (it has a default value of 1 in my database). featured_status TRUE Photo class has these methods class Photo < ApplicationRecord belongs_to :user has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :image, content_type: /Aimage/.*z/ validates :image, :title, ...

Rails 5 Jquery stops working on redirect

Rails 5 Jquery stops working on redirect So I'm working with Rails 5.1 to create a web app and I'm using a CSS checkbox hack to open a navigation menu. I have a button (on root_path) which, when clicked, uses Jquery to check the box from another area. It works when going to the page, but when I redirect to another page, it stops working. But the console still outputs true/false when I click the button logging whether the checkbox is checked or not. So the button functions seem to work on-click, but the checkbox doesn't show as checked. I've spent a lot of time playing with the jquery, turning off turbolinks on the home button which refreshes, etc. Curious if anyone has a way to get around this or if rails 5 is finicky with this stuff. Here is the snippet for the two buttons in _index.html.erb <div class="index__content--buttons"> <%= link_to("Find Out More", root_path, :class => "btn btn--primary", data: { no_turbolink: tr...

Best practice for clearing a form field when using Postgres Array column in a Rails 5.2 app?

Best practice for clearing a form field when using Postgres Array column in a Rails 5.2 app? I'm building a Rails 5.2 application that has a Postgres array column to store tags on a Post model. The migration I created looks like this... class AddTagsToPosts < ActiveRecord::Migration[5.2] def change change_table :posts do |t| t.string :tags, array: true, default: end end end Since setting the default value is required (?...I failed to find a way to get a PG array column to work without setting the default value of tags to an empty array), what is the best practice to remove the default value () from being auto filled on a Rails new/edit form without using JS? 1 Answer 1 <% 3.times do |num| %> <%= form.text_field :tags, multiple: true, class: "form-control", value: @post.tags[num] %> <% end %> By clickin...

Bundler could not find compatible versions for multiple gems that seem to fall within range of requirements

Bundler could not find compatible versions for multiple gems that seem to fall within range of requirements I'm trying to use a gem spree , which depends on kaminari (~> 1.0.1) . In my Gemfile.lock , I have kaminari (= 1.1.1) . This satisfies the requirement for spree , since it's greater than or equal to the last digit. However, I'm getting this error when I try to bundle: spree kaminari (~> 1.0.1) Gemfile.lock kaminari (= 1.1.1) spree Bundler could not find compatible versions for gem "kaminari": In snapshot (Gemfile.lock): kaminari (= 1.1.1) In Gemfile: activeadmin (~> 1.3) was resolved to 1.3.0, which depends on kaminari (>= 0.15) rails_admin (~> 1.3) was resolved to 1.3.0, which depends on kaminari (< 2.0, >= 0.14) spree (~> 3.5.0) was resolved to 3.5.0, which depends on spree_core (= 3.5.0) was resolved to 3.5.0, which depends on kaminari (~> 1.0.1) Running `bundle update` will rebuild ...

Ngnix still seeing welcome screen after configuration

Ngnix still seeing welcome screen after configuration I have set up and deployed an application using Capistrano, Nginx, Passenger and set up the server and ngnix config file, however, I'm still seeing the Welcome to ngnix welcome screen. Welcome to ngnix Here is what I have in the /etc/nginx/sites-enabled/default file /etc/nginx/sites-enabled/default server { listen 80; listen [::]:80 ipv6only=on; server_name IP; passenger_enabled on; rails_env production; root /home/poladmin/poetry-out-loud-v2/current/public/; # redirect server error pages to the static page /50x.html error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } I have restarted Ngnix but I'm still not seeing the website. 1 Answer 1 Sounds like Nginx is serving you the content from it's installati...

Rails controller issue when updating multiple records

Rails controller issue when updating multiple records I am trying to update multiple records using checkboxes. I manage to display the edit_multiple page properly, but when i validate it, I have the error. I suspect it has to do with the controller, looking at the error message.(The column Group_id should be updated for each of the selected row) Group_id Anybody knows what is wrong ? Thank you The error: ActiveRecord::RecordNotFound in DistribsController#update_multiple Couldn't find Distrib with 'id'= Extracted source (around line #75): def update_multiple @distribs = Distrib.find(params[:distrib_ids]) @distribs.reject! do |distrib| distrib.update_attributes(params[:distrib_ids].reject {|k, v| v.blank?}) end Application Trace | Framework Trace | Full Trace app/controllers/distribs_controller.rb:75:in `update_multiple' Request Parameters: {"utf8"=>"✓", "_method"=>"put", "authenticity_token...

Rails *Completed 406 Not Acceptable" in production ..working in Staging

Rails *Completed 406 Not Acceptable" in production ..working in Staging I am stuck with an error " Completed 406 Not Acceptable " in the production server which I am not facing in the staging server . Same code is working fine in staging but not working in production .Both environment has same gems installed . I am using a rails version 3.0.10. In my production environment , the GET request is processed as a html but in staging it is processed as js .I have defined the respond_to block only for js format . I am not sure why it is behaving differently in two environments. Also I have tried adding the defaults format as js in the routes.rb but that also is not working. match 'releases/cycle_paginate', :to => 'releases#cycle_paginate', :defaults => { :format => 'js' } But this is also not working . Below is the log for production and staging . Production: Started GET "/releases/cycle_paginate/2?id=4" for 10.30.10.67 at Wed Aug 14 0...

Image Watermark MiniMagick & Rails 5.2

Image Watermark MiniMagick & Rails 5.2 I am trying to watermark the product images from a model. I have set static images for testing but I am getting an error and I don't understand why. Can anyone assist in why I am getting this error: undefined method `composite' for "CIAO12.png":String Current Setup: Rails 5.2 gem 'mini_magick', '~> 4.8' (Included in the Gemfile) Brew install imagemagick (Successful) Code is testing on static images but will be change to the product image instead of the 'CIA012.png' image. Show Action <div class="card-body"> <h5 class="card-title"><%= @product.product_name %></h5> <% if @product.image.attached? %> <%= image_tag(@product.watermark) %> <% end %> </div> Product Model def watermark first_image = "CIAO12.png" second_image = "watermark.png" result = first_image.composite(second_image) do |c| c.compos...

react-rails asset pipeline image path

react-rails asset pipeline image path I'm using the react-rails gem, and I'm having trouble figuring out how to load images from the asset pipeline. I handle this currently by using the .js.jsx.erb extension, but as far as I know this is unconventional. (am I correct?) .js.jsx.erb Sometimes I just use an empty div and and set the div's background-image property as the image I intend to use. background-image What is the best way to go about loading images to react components when using react-rails ? react-rails 1 Answer 1 There are two ways to import image... 1) If you are direct using jsx.erb or js.erb file... jsx.erb js.erb var image_path = "<%= asset_path(my_image.png) %>" OR render: function() { return ( <img src={"<%= asset_url('path/to/image.png') %>"} /> ) } 2) Passing as props Through .erb file to .js.e...

How to sandbox a rails application so that dependencies are installed locally without having to re-run bundle install

How to sandbox a rails application so that dependencies are installed locally without having to re-run bundle install I'm trying to sandbox a rails application so that i can port it over to other machines without having to re-bundle. Is there a way for rails to pull in dependencies locally to self-sustain? 1 Answer 1 All dependencies are stored in the Gemfile.lock. All gems stored in ruby directory. You can run once bundle install to create Gemfile.lock. Then save Gemefile.lock and pack a directory with gems. After it you can copy your pack to server and deploy you application. but if you move directory to a different environment, say docker, and say you don't have internet, you wouldn't be able to bundle install. – user2167582 Jun 30 at 13:34 ...