Thursday, May 26, 2016

Rails - how to place text onto an image within a code loop | Fixed issues

Rails - how to place text onto an image within a code loop | Fixed issues


Rails - how to place text onto an image within a code loop

Posted: 26 May 2016 06:53 AM PDT

I'm building an events site using rails. For my index page I have a code loop showing an image, the event title and the date for each event. I need to show the title and date ON TOP OF the image. The code blocks for the title and date are wrapped in h2 and h3 tags respectively. I'm not entirely sure how to style this properly.

My html page is set out as follows -

index.html.erb - events

<div class="container">   <div class="row">      <div class="col-md-12">          <div class="events">                  <% @events.each do |event| %>                  <li><%= link_to (image_tag event.image.url), event, id: "image" %></li>              <div id="text">                   <h2><%= link_to event.title, event %></h2>                  <h3><%= link_to event.date.strftime('%A, %d %b %Y'), event %></h3>              <% end %>              </div>            </div>                    </div>     </div>      </div>   

My CSS for the image section is as follows -

Events.css.scss

div.container {  width: 100%;    }           .col-md-12 {          width: 100%;      }         div.events img {      width: 350px;      height: 350px;      margin: 20px;      display: inline-block;      border-radius: 25px;      }     div.events li {        float: left;      list-style-type: none;  }     

What do I need to do to place the text elements of this code loop onto the relevant image?

Best practice for waiting for image processing?

Posted: 26 May 2016 06:59 AM PDT

I've got a model that uses Carrierwave and CarrierwaveBackgrounder for image processing:

mount_uploader :background, BackgroundUploader  process_in_background :background  

So when an resource gets created I would like to wait for the Backgrounder to finish processing the image and then redirect to the newly created resource.

All I can think of now seems very dirty to me:

sleep(2.0) while @page.background.large.file.exists?  

But that could maybe even cause timeouts.

Any other/better suggestions?

ActiveRecord accessing database when there are restrictions

Posted: 26 May 2016 06:44 AM PDT

There is a postgres db server A, which has access only from one node B. But any computer is able to access and login to B. How do I establish connection using ActiveRecord to the db server A from any node (which is not B) in a Ruby script?

How to check elasticsearch tokens after running a query in Rails?

Posted: 26 May 2016 06:44 AM PDT

My problem is the following:

I run an elasticsearch query in a rails app using specific settings to my index and my search analyzer, the problem is that it doesnt return any results in the app, in the other hand when i try to run it directly from my elasticsearch docker, i have tokens returned. If i use these tokens in my app query, i get results...

so this is my elasticsearch query:

curl -XGET 'localhost:9200/development-stoot-services/_analyze?analyzer=search_francais' -d 'cours de guitare'  {"tokens":[{"token":"cour","start_offset":0,"end_offset":5,"type":"<ALPHANUM>","position":1},{"token":"guitar","start_offset":9,"end_offset":16,"type":"<ALPHANUM>","position":3}]}  

here is the query from my rails app to elasticsearch:

query = {     "query" : {       "bool" : {         "must" : [           {             "range" : {               "deadline" : {                 "gte" : "2016-05-26T10:27:19+02:00"               }             }           },           {             "terms" : {               "state" : [                 "open"               ]             }           },           {             "query_string" : {               "query" : "cours de guitare",               "default_operator" : "AND",               "fields" : [                 "title",                 "description",                 "brand",                 "category_name"               ]             }           }         ]       }     },     "filter" : {       "and" : [         {           "geo_distance" : {             "distance" : "40km",             "location" : {               "lat" : 48.855736,               "lon" : 2.32927300000006             }           }         }       ]     },     "sort" : [       {         "created_at" : "desc"       }     ]   }   

the last query does not return any result, but if i try a query with the tokens returned by elasticsearch ('cour', 'guitar') i have expected results. So i guess there is a problem between rails and elasticsearch that i dont find... Can anyone help on that ?

How to use rails act_as_sortable gem, with several belongs_to relations

Posted: 26 May 2016 06:39 AM PDT

I have an Image model, which uses activerecord-sortable gem to easily reorder images by position.

My product model is linked to the image model, and can be re-ordered with config[:relation] option of activerecord-sortable.

It works fine, but I now want to add a Shop model, with the same relationship as product, in which images can also be reordered.

Here is my image Model

class Image < ActiveRecord::Base    acts_as_sortable do |config|      config[:relation] = ->(instance) {instance.product.images}    end    belongs_to :product    belongs_to :shop  

Is there any way I can specify to activerecord-sortable that my Image model must use several relationships ?

I have tried that :

  acts_as_sortable do |config|      config[:relations] = [->(instance) {instance.product.images}, ->(instance) {instance.product.images}]    end  

But it doesn't work

RSpec Capybara - Request test. Need advise

Posted: 26 May 2016 06:46 AM PDT

Two things which i don't understand at all.

1) first example: visit path - fail and get path - pass, why? Visit - capybara and get - rspec helper, right?

  describe "in the Users controller" do     describe "visiting the users page as non-signed" do       before { get users_path }       #before { visit users_path }       it { expect(response.status).to eql(302) }       it { expect(response).to redirect_to(new_user_session_path) }     end     describe "visiting the user[:id = 1] profile page as non-signed" do       before { get user_path(User.where(admin: true)) }       #before { visit user_path(User.where(admin: true)) }       it { expect(response.status).to eql(302) }       it { expect(response).to redirect_to(new_user_session_path)  }     end   end  

With get some_path_here -> test pass

But with visit some_path_here ->

enter image description here

2) second example:

after login as regular user, should not have menu like admin. It looks like no differense between user and admin

  describe "as signed admin" do      let(:admin) { create(:admin) }      before do        log_in admin      end      it { should have_link("Users", href: users_path)}      it { should have_link("Orders", href: orders_path)}      it { should have_link("Current Menu", href: products_path)}      it { should_not have_link("Dashboard", href: new_order_path)}    end      describe "as signed user" do      let(:user) { create(:user) }        before do          log_in user        end      it { should have_link("Profile", href: user_path(user))}      it { should have_link("Dashboard", href: new_order_path)}      it { should_not have_link("Users", href: users_path)}      it { should_not have_link("Current Menu", href: products_path)}    end      include ApplicationHelper    def log_in(user)   visit root_path   fill_in 'Email', with: user.email   fill_in 'Password', with: user.password   click_button 'Sign in'  end  def sign_up(user)    visit new_user_registration_path   fill_in 'Username', with: user.username   fill_in 'Email', with: user.email   fill_in 'Password', with: user.password   fill_in 'Password confirmation', with: user.password   click_button 'Sign up'  end  

enter image description here

Refactoring ruby code , nested loops for exporting to csv

Posted: 26 May 2016 06:13 AM PDT

I'm new to ruby, and I have to export information to csv. I wrote this code and I don't really like, don't know how can I refactored and get rid of the nested loops. my relations are like the following : Order has many moves, moves have many stops. and I have to export all of this to csv, so as a result I will have multiple lines for the same order!

  def to_csv      CSV.generate(headers: true) do |csv|        csv << h.t(self.first.exported_attributes.values.flatten) # headers        self.each do |order|          order.moves.map do |move|            move.stops.map do |stop|              order_data = order.exported_attributes[:order].map do |attributes|                order.public_send(attributes)              end              move_data = order.exported_attributes[:move].map do |attributes|                move.decorate.public_send(attributes)              end              stop_data = order.exported_attributes[:stop].map do |attributes|                stop.decorate.public_send(attributes)              end              csv << order_data + move_data + stop_data            end          end        end      end    end  

it's not a good quality code ..

How to retry if jobs in cron fails?

Posted: 26 May 2016 06:07 AM PDT

I am using whenever gem to schedule my cron job.

I am having some import services which daily download files from ftp server and parse them and store them to database.

This services have to run daily so I have made a cron job for the same.

Code:

set :output, 'log/cron_log.log'  every 1.day at: '5am' do    runner 'BackOffice::ImportServices::Import.call'    runner 'Notifier.send_task_complete_message_via_email("Task completed successfully").deliver_now'  end  

The Backoffice service calls two services one after the another which saves different data.

In those services I have handled exception and made retries after 1 minutes and after 3 retry counts I send a failure email to admin.

My question is I want to delay the failed service after specific interval of time say 2 hours. So, how do I schedule or delay that job if some service fails for that same service.

Note: I can't make retry in rescue block to be 2 hours as other services would be stuck.

How do I achieve this task using whenever gem, or is there another gem that would help me achieve this task.

Any suggestion on how to resolve this problem would be of great help.

Thank You!

Rails - eager loading with has_many_through association

Posted: 26 May 2016 06:41 AM PDT

I have a very simple has_many_through association as follows:

class Retailer < ActiveRecord::Base    has_many :retailer_tags    has_many :tags, through: :retailer_tags  end    class Tag < ActiveRecord::Base    has_many :retailer_tags    has_many :retailers, through: :retailer_tags  end    class RetailerTag < ActiveRecord::Base    belongs_to :retailer    belongs_to :tag  end  

In the index of my retailers controller, I want to display a list of all the retailers with their associated tags. If I just have in my controller @retailers = Retailer.all and then loop over all the retailers in my view, I have a N+1 queries problem.

I can solve this issue using Postgresql directly and it works fine, but I would like to understand how to do it in Rails.

When I do @retailers = Retailer.eager_load(retailer_tags: :tag).all (or any of includes / preload / joins), I still get N+1 queries.

What am I doing wrong? Thanks for you help

Sidekiq Redis database keys increasing over time

Posted: 26 May 2016 05:52 AM PDT

I am currently using Sidekiq with my Rails app in production along with an ElasticCache Redis database. I've noticed recently that when monitoring the CurrItems metric using the AWS tools, I see the number of items gradually increasing over time in an almost step-like way:

enter image description here

However, when I look at the jobs in queue in the Sidekiq dashboard, I don't see anything backing up at all. I see 0 jobs in queue, 0 busy, 0 scheduled.

The step-like increase seems to happen at a very particular time each day (right at the end of the day), which made me think it might be related to a chron job/clockwork process I have running. However, I only have 4 jobs that run once a day and none of them run during that time or even near that time. Just for good measure though, here is my clock.rb file (I have shorted all the job descriptions and class and method names for simplicity's sake):

module Clockwork    every(30.seconds, 'Task 1') { Class.method }    every(30.seconds, 'Task 2') { Class.method }    every(10.minutes, 'Task 3') { Class.method }    every(1.day, 'Task 4', :at => '06:00', :tz => 'EST') { Class.method }    every(10.minutes, 'Task 5') { Class.method }    every(1.day, 'Task 6', :at => '20:00', :tz => 'UTC') { Class.method }    every(1.day, 'Task 7', :at => '20:00', :tz => 'UTC') { Class.method }    every(1.day, 'Task 8', :at => '20:00', :tz => 'UTC') { Class.method }    every(1.hour, 'Task 9') {Class.method}    every(30.minutes, 'Task 10') {Class.method}    every(30.minutes, 'Task 11') {Class.method}    every(1.hour, 'Task 12') {Class.method}  end  

I'm not quite sure where this is coming from. Maybe Sidekiq isn't removing the keys from the database once the job is complete?

Another potential helpful piece of information is that I'm running 4 workers/servers. Here is my Redis configuration:

if (Rails.env == "production" || Rails.env == "staging")      redis_domain = ENV['REDIS_DOMAIN']        redis_port   = ENV['REDIS_PORT']        redis_url = "redis://#{redis_domain}:#{redis_port}"        Sidekiq.configure_server do |config|        ActiveRecord::Base.establish_connection(            adapter: "postgresql",            encoding: "unicode",            database: ENV["RDS_DB_NAME"],            pool: 25,            username: ENV["RDS_USERNAME"],            password: ENV["RDS_PASSWORD"],            host: ENV["RDS_HOST"],            port: 5432        )          config.redis = {          namespace: "sidekiq",          url: redis_url        }        end        Sidekiq.configure_client do |config|        config.redis = {          namespace: "sidekiq",          url: redis_url        }      end  end  

Anyone know why this could be happening?

rails - how to translate what is within a ruby code in a form format?

Posted: 26 May 2016 06:15 AM PDT

I have a ruby code.

<%= f.label "Email *" %>  

And I want to translate the English word "Email" to Japanese word because I am currently internationalizing my website written in English.

I tried the following.

<%= f.label "<%= t(:email) %> *" %>  

However, it did not work. What should i do?

ActiveRecord::StatementInvalid (NoMethodError: undefined method `query' for nil:NilClass: ROLLBACK)

Posted: 26 May 2016 06:12 AM PDT

I have admin control with devise. Admin can create multiple clients with one unique email and password for devise authentication. For each client, new schema will be created with client id e.g. apple_client_1 with 5 fix client related tables. When client log in with this email and password, transactions of their 5 models/table will be stored in their own database. So we have to manage 2 database, first is global database for authentication of admin and client and other local database for that particular client. So how can i manage it?

after_create :create_client_schema

def create_client_schema   schema_name = "apple_client_#{self.id}"   schema_sql = %{CREATE SCHEMA #{schema_name}}   ActiveRecord::Base.connection.execute schema_sql   ActiveRecord::Base.establish_connection(    {      adapter: ENV['DB_ADAPTER'],      database: schema_name,      host: ENV['DB_HOST'],      username: ENV['DB_USERNAME'],      password: ENV['DB_PASSWORD']    }   )   load "#{Rails.root}/db/client_schema.rb"  end  

Rails multiple objects select box

Posted: 26 May 2016 06:40 AM PDT

I have an index page where I am listing out all the objects(post) from a collection of objects(@posts) which has come from a post controller.

I want to add a checkbox to each of those post objects so that the user can select which one of these objects they want to export via an export controller I have created.

How can I setup a form so that it posts the selected object id's to this export controller?

Thanks in advance.

How to install nokogiri 1.6.7.2 on windows

Posted: 26 May 2016 06:13 AM PDT

I have gone through various links on stack overflow but don't get the solution to install nokogiri 1.6.7.2 gem with ruby 2.3.0

I have installed ruby 2.3.0 along with the DevKit. Still I am unable to run bundle install command it always show below error.

"An error occurred while installing nokogiri (1.6.7.2), and Bundler cannot continue. Make sure that gem install nokogiri -v '1.6.7.2' succeeds before bundling."

I have run following devkit commands:

ruby dk.rb init  ruby dk.rb review  ruby dk.rb install  

Its run successfully and all ruby versions show.

C:/Ruby200 C:/Ruby22 C:/Ruby23

Though I have installed ruby 2.2.4 also but still when run bundle install it shows: ERROR: Error installing nokogiri: nokogiri requires Ruby version < 2.3, >= 1.9.2.

I am using windows 7 32-bit system. Due to this issue unable to install bundle. Please help. Thanks in Advance

"no implicit conversion of nil into String"in the Search Module of Redmine

Posted: 26 May 2016 05:02 AM PDT

On the redmine of my company, there is this bug where I get an internal error if I want to search into a project.

Here is the log corresponding to the error:

Processing by SearchController#index as HTML    Parameters: {"utf8"=>"✓", "issues"=>"1", "q"=>"test", "id"=>"sprint"}    Current user: me (id=60)  Completed 500 Internal Server Error in 85.0ms    TypeError (no implicit conversion of nil into String):    lib/plugins/acts_as_searchable/lib/acts_as_searchable.rb:126:in `search'    app/controllers/search_controller.rb:74:in `block in index'    app/controllers/search_controller.rb:73:in `each'    app/controllers/search_controller.rb:73:in `index'  

The lines corresponding to the error in the controller are :

 if !@tokens.empty?        # no more than 5 tokens to search for        @tokens.slice! 5..-1 if @tokens.size > 5          @results = []        @results_by_type = Hash.new {|h,k| h[k] = 0}          limit = 10        @scope.each do |s|          r, c = s.singularize.camelcase.constantize.search(@tokens, projects_to_search,            :all_words => @all_words,            :titles_only => @titles_only,            :limit => (limit+1),            :offset => offset,            :before => params[:previous].nil?)          @results += r  

Here is my config :

Environment:    Redmine version                2.6.9.stable    Ruby version                   2.3.0-p0 (2015-12-25) [x86_64-linux]    Rails version                  3.2.22    Environment                    production    Database adapter               PostgreSQL  SCM:    Git                            1.9.1    Filesystem                       Redmine plugins:    no plugin installed  

What is interesting is that when I search only one letter, i'm redirected on the search page, but I don't have an internal error.

I'm very new to Redmine developpement and to Ruby, I was just assigned to try to fix this bug. Do any of you have an idea of how to fix it ?

Thanks.

Getting location(city, state) from ip_address for bulk data with rake task

Posted: 26 May 2016 04:54 AM PDT

I have an x users with their last_sign_in_ip, can i get their location details using their ip_address with rake task? I am using rails and geocoder gem.

undefined method `each' for nil:NilClass in update method

Posted: 26 May 2016 06:14 AM PDT

I have an Audi model in my ruby on rails application in which there are many fields like model, variant, car image, exterior, interior, brochure etc. When I try to update some attributes(not all), then it gives undefined method `each' for nil:NilClass in exterior and interior image section.

More specifically, the issue is here:

params[:exterior_image].each { |exterior_image| ... }  

update method:

def update      respond_to do |format|        @audi_model = AudiModel.find(params[:id])        if @audi_model.update(audi_model_params)              model_exterior_image_names = @audi_model.car_exterior_images.map{|m|m.exterior_image_file_name}              params[:exterior_image].each { |exterior_image|              unless model_exterior_image_names.include?(exterior_image.original_filename)              @audi_model.car_exterior_images.create(exterior_image: exterior_image)              end              }              model_interior_image_names = @audi_model.car_interior_images.map{|m|m.interior_image_file_name}              params[:interior_image].each { |interior_image|              unless model_interior_image_names.include?(interior_image.original_filename)              @audi_model.car_interior_images.create(interior_image: interior_image)              end              }          format.html { redirect_to @audi_model, notice: 'Audi model was successfully updated.' }          format.json { render :show, status: :ok, location: @audi_model }        else          format.html { render :edit }          format.json { render json: @audi_model.errors, status: :unprocessable_entity }        end      end  

Request parameters :

{"utf8"=>"✓",   "_method"=>"patch",   "authenticity_token"=>"3qiq/VNRNk369HEZr0Eb/R5iuhKgGTpJCfOh8ek3nGWLeU+zDNDvEAwJ3SvlLb0h4gVql549d3GnCV9Fa/ZnNA==",   "audi_model"=>{"car_model"=>"TT",   "variant"=>"Diesel",   "introduction"=>"test",   "engine"=>"test",   "video_url"=>"https://www.youtube.com/watch?v=N3x_RZlOmK0",   "brochure_url"=>"http://www.audigurgaon.in/brochure/tt-brochure-2014.pdf"},   "commit"=>"Update Audi model",   "id"=>"19"}  

How to update form fields real time in rails [on hold]

Posted: 26 May 2016 03:58 AM PDT

I have been building a CMS for our business application and I have been wondering if there are ways / what the best practices to update form fields in rails in real time?

I find out that there are many long forms in my application and users often forgot to hit the save button. I have been looking at gems like sync and cells. I wonder if I am in the right direction.

How to split Devise edit page form into two pages?

Posted: 26 May 2016 05:20 AM PDT

I'm trying to figure how to split form from Devise edit page into two pages as it has too many fields right now. So the goal is for users to be able to update their profile information from separate pages. I'm fairly new to Rails so I don't understand what's going... I haven't created new controller for this purpose, I'm using existing Devise controller... The error I'm getting is that there is no edit_profile action defined in Registrations Controller even though there is..

What I did:

Created a new view style.html.erb with a form and it's under registrations views. I just copied to form from existing edit.html.erb

<%= form_for resource, as: resource_name, url: registration_path(resource_name), layout: :horizontal do |f| %>  

Added this to routes:

devise_for :users, class_name: 'FormUser', :controllers => { omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations' }    **get "users/style" => "registrations#edit_profile", as: "edit_profile"**  

Here is my registration controller so far:

class RegistrationsController < Devise::RegistrationsController    prepend_before_filter :authenticate_scope!, only: [:edit, :profile, :update, :destroy]      protected         def update_resource(resource, params)      if resource.encrypted_password.blank? # || params[:password].blank?        resource.email = params[:email] if params[:email]        if !params[:password].blank? && params[:password] == params[:password_confirmation]          logger.info "Updating password"          resource.password = params[:password]          resource.save        end        if resource.valid?          resource.update_without_password(params)        end      else        resource.update_with_password(params)      end    end        def edit_profile        end      end  

Quikchex test application

Posted: 26 May 2016 03:36 AM PDT

I have cleared the first round of quicl kChex, they have given me a test.

https://youtu.be/CBIigC5WHU4

Do any one have any idea how we can do that, such searching algorithm.

Refreshing partial div's with java on a set interval

Posted: 26 May 2016 04:14 AM PDT

I have one partial on my index.html.erb with sql query from a remote database and another one with csv read from file. Both partials are auto refreshing with java script, but only sql partial refresh works correct and keeps refreshing data, csv partial does not update values till the full page refresh. Chrome console Network section shows that both partials keeps refreshing on set interval with status 200(ok). Why does csv partial not updating the values?

Aaaa controler:

require 'tiny_tds'  require 'csv'    class AaaaController < ApplicationController      def index      client2 = TinyTds::Client.new username: 'xxxx', password: 'xxx',                                   host: 'xx.xxx.x.xxx', port: xx, timeout: xx,                                   database: 'xxxxx'          @gedi=client2.execute("select xxx")                       oranz = CSV.read("/path/tofile.csv")       @oranz1 =   oranz.join(',')         melyn = CSV.read("/path/tofile.csv")       @mely1 = melyn.join(',')         akva = CSV.read("/path/tofile.csv")       @kava1 = akva.join(',')         saka = CSV.read("/path/tofile.csv")       @sa1 = saka.join(',')      def ged          client2 = TinyTds::Client.new username: 'xxxx', password: 'xxx',                                   host: 'xx.xxx.x.xxx', port: xx, timeout: xx,                                   database: 'xxxxx'          @gedi=client2.execute("select xxx")     render :partial => 'aaaa/ged', :locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]  end      def sal       oranz = CSV.read("/path/tofile.csv")       @oranz1 =   oranz.join(',')         melyn = CSV.read("/path/tofile.csv")       @mely1 = melyn.join(',')         akva = CSV.read("/path/tofile.csv")       @kava1 = akva.join(',')         saka = CSV.read("/path/tofile.csv")       @sa1 = saka.join(',')           render :partial => 'aaaa/sal', :locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]   end  end  

script for csv partial:

<script type="text/javascript">   $(document).ready(           function() {            setInterval(function() {              $('.refresh').load('/aaaa/sal');          }, 300000);      });  </script>  

console:

Started GET "/aaaa/sal" for 127.0.0.1 at 2016-05-26 14:07:14 +0300  Processing by AaaaController#sal as HTML    Rendered aaaa/_sal.html.erb (1.2ms)  Completed 200 OK in 52ms (Views: 2.9ms | ActiveRecord: 0.0ms)  

how to get the id of the @mentioned_name from the Jquery at-who plugin

Posted: 26 May 2016 03:06 AM PDT

I'm working on a small project with ruby 2.2 and rails 4.2. I'm trying to implement the @mention_name feature like Facebook. I'm using the following for the same https://github.com/ichord/At.js

Now to load the data to the plugin i use an instance variable say @username. which is hash of user_id and user_name. i iterate over the object and load the data of plugin with @username.values.

what i want is when i use @ in the text area i have to store the ids of the users who where selected and on submit i have to store the user_ids in the db field say custom_sharing_ids

I have implemented till showing the drop down and selected the usernames from the list of names.

 def get_all_user_names      @usernames= {}      user_obj = User.all      user_obj.each do |user|        # binding.pry         @usernames[user.id] = user.get_display_name      end     @usernames  end   

And this is my .html.erb file

<script>      $(function(){      data = <%= raw @usernames.values %>;      $('textarea#ta_custom_sharing').atwho({at:"@", 'data':data});      });  </script>  

which gives me hash {1 =>"A", 2 => "B"}. now when i select say A, i have to pass the user_id "1" to the controller and save.

Any help on this will be appreciated.

Date.today updation issue in rails and postgresql

Posted: 26 May 2016 03:39 AM PDT

I have rake task which is having following line:

p "----------#{Date.today}"  p "--add_date---- #{add_date}"    Finder.find_by_app_id(lr.app_id).update_attributes(:last_delivery_at => Date.today,:next_run_date => add_date)  

which gives in console

"----------2016-05-26"

"--add_date---- 2016-05-27 00:00:00 +0530"

but in Postgresql database : last_delivery_at : 2016-05-25 next_run_date : 2016-05-26 (it supposed to be 2016-05-27 as per my logic)

how this date is getting -1 day when it is updating in database?

Ransack sorting associations one to many

Posted: 26 May 2016 06:09 AM PDT

I was able to make the search associations works, but the sorting didn't work the same way: example from my model:

  def having_starting_countries(*countries)      joins(locations: :country).where('countries.name IN (?)', countries).where('stops.position = 1')    end      def by_origin      binding.pry      joins(:locations).where('stops.position = 1')    end        def ransackable_scopes(_user = nil)      [:having_starting_countries, :by_origin]    end  

having_starting_countries search filter is working while by_origin is not.

and the link to the sort is correct. and I have to mention that, my case is not one to one, like order.customer.name . but it's like: order.moves.first.stops.first.address any idea ?

Update: I have a grid and I want the sort to be based on address field inside the stop.

Rails- paperclip- NoMethodError

Posted: 26 May 2016 03:30 AM PDT

I'm trying to make a movie review app in rails. This includes adding movie image and text fields. I'm using the paperclip gem for image upload. I am getting this error while adding movie.

NoMethodError in Movies#create

Showing - MovieReview/app/views/movies/_form.html.erb where line #2 raised:    undefined method `map' for nil:NilClass  Trace of template inclusion: app/views/movies/new.html.erb    Rails.root: /Review/MovieReview  

I am rendering a form partial in my movies/new,html.erb. Following is code snippet from movies/_form.html.erb

<%= simple_form_for @movie, :html => { :multipart => true} do |f| %>     <%= select_tag(:category_id, options_for_select(@categories), :prompt => "Select a Category") %>      <%= f.file_field :movie_img %>    <%= f.input :title, label: "Movie Title" %>    <%= f.input :description %>    <%= f.input :director %>    <%= f.button :submit %>  

Movies Controller

class MoviesController < ApplicationController    def new          @movie = current_user.movies.build          @categories = Category.all.map{ |c| [c.name, c.id] }      end        def create          @movie = current_user.movies.build(movie_params)          @movie.category_id = params[:category_id]            if @movie.save              redirect_to root_path          else              render 'new'          end      end  

PS: I have added image parameter in the movie_params method which is their in the private section- Following is the code snippet

def movie_params          params.require(:movie).permit(:title, :description, :director, :category_id, :movie_img)      end  

Movies Model

class Movie < ActiveRecord::Base      belongs_to :user      belongs_to :category      has_attached_file :movie_img, styles: { movie_index: "250x350>", movie_show: "325x475>" }, default_url: "/images/:style/missing.png"    validates_attachment_content_type :movie_img, content_type: /\Aimage\/.*\Z/  end  

Category Model

class Category < ActiveRecord::Base      has_many :movies  end  

AWS Opsworks executing deploy hooks in "setup" stage

Posted: 26 May 2016 02:15 AM PDT

I am setting up a rails 4 app on AWS opsworks.

When I boot up an instance, I see that the deploy hooks are running in the "setup" lifecycle event of opsworks rather than the deploy event.

I am facing problems in running asset precompile because of this. I cannot get expected behaviour because these callbacks happen in the setup lifecycle. Any help is appreciated.

Rails 3 Streaming Video or Rails HTTP Streaming

Posted: 26 May 2016 06:43 AM PDT

I recently implemented JP video player or J Player in my Rails 3 app to stream video tutorials, but issue is video is not streamed in chunks means if size of video is 100MB then after that 100MB gets downloaded on browser then only video will play. To overcome this issue i have implemented http streaming using this rails cast http://railscasts.com/episodes/266-http-streaming Even then the video is getting fully downloaded. I am not able to understand what wrong i have done. When i am using curl -i command it shows me Transfer-Encoding: chunked but it is not working as youtube or other video sites work.

muliple rails app in one server

Posted: 26 May 2016 02:11 AM PDT

I have a server with 20Cores / 40Threads. I used to have only one website app (rails / unicorn / nginx , 40 workers) on it and everything was working well

recently I added a new website app (rails / unicorn / nginx, 2 workers) and since this, I have much less requests for my first website.

htop stats seems to be normal.

enter image description here

How can I find out where is the bottle neck ? Maybe it is link with network, as my second apps is making external requests ? Or maybe IO access as my second apps is also reading and writting in the ssd disk

thanks

time select not loading into database

Posted: 26 May 2016 02:10 AM PDT

i am trying to add a set of hours to my database as can be seen below, though i am getting the follow error. from the looks of the logs it also appears that it is the complete date time string, though i only want time

ActiveRecord::MultiparameterAssignmentErrors (2 error(s) on assignment of multiparameter attributes [error on assignment [2016, 5, 26, 9, 0] to open_time (undefined method `Melbourne' for Time:Class),error on assignment [2016, 5, 26, 17, 0] to close_time (undefined method `Melbourne' for Time:Class)]):    app/controllers/admin/merchants_controller.rb:34:in `update'  

migration

class CreateTradingHours < ActiveRecord::Migration    def change      create_table :trading_hours do |t|        t.integer :merchant_id        t.integer :weekday        t.time :open_time        t.time :close_time        t.boolean :trades      end      add_index :trading_hours, :merchant_id    end  end  

form

= form.fields_for :trading_hours do |hours_fields|        %li.mdl-list__item.mdl-list__item--two-line          %span.mdl-list__item-primary-content            = hours_fields.label :weekday            %span.mdl-list__item-sub-title              OPEN              = hours_fields.time_select :open_time, {:default => {:hour => '9', :minute => '00'}}              CLOSE              = hours_fields.time_select :close_time, {:default => {:hour => '17', :minute => '00'}}  

undefined method `all' for {:conditions=>{:retailer_id=>[1, 2]}}:Hash In rails Engine

Posted: 26 May 2016 06:07 AM PDT

I am getting an error while fetching the data from the model, Here is the scenario I have created a "ProductSearch" Engine and inside the ProductSearch I have controllers, models, helpers, and views.

Now the controller method gives an error while executing below is the code for controller method

  def stores_in_mall      @stores ||= TenantRetailigenceRetailer.          for_property(@property).all(:include => :retailer, :order => 'retailers.name').          reject{ |s| s.retailer.nil? || s.retailer.suite.nil? }    end  

Here is the code for ProductSearch Model

module ProductSearch    class TenantRetailigenceRetailer < ActiveRecord::Base        belongs_to :retailer        belongs_to :retailigence_retailer        attr_accessor :tenant_id, :retailigence_retailer_id        scope :for_property, lambda{ |property|                                   { :conditions => { :retailer_id => property.retailers.map(&:id) } }                                 }          def name          retailer.name        end    end  end  

No comments:

Post a Comment