jeudi 29 mars 2018

Submit button disabled after rendering create action rails

I am building a job app with Rails. In my job 'new' page. I have a preview functionality where a user can click a 'preview button' to see how the job would look like when posted. The preview page opens in another tab. The user is then supposed to return back to the job 'new' page, to either post the job or make edits.

The main issue is that, after I click on the preview button and the new tab opens, both the 'preview' and 'post job' button on the job 'new' page become disabled and and I cant click on 'post' to save the job to the database. This is my controller 'create method'

  def create
    @job = Job.new(job_params)
      if params[:previewButt] == "Preview"
        flash[:alert] = "This is a PREVIEW of your job posting. Go back to the previous tab to Post the job or make edits."
        render :create
      elsif
        params[:createButt] == "Post Job"
        @job.save
        redirect_to root_path
      else
        render :new
      end
  end

In my job 'new' page, these are the two buttons i have,

 <div class="col-md-9 text-center" style="margin-top: 110px;">
   <%= f.button :submit , name: "previewButt", value: "Preview", 
 formtarget:"_blank" %>
   <%= f.button :submit , name: "createButt", value: "Post Job", class: 
 "btn btn-success post-btn" %>
 </div>

I need to make sure that, the two buttons are still able to function even after a user clicks on preview button.

How to retain data in input fields after a page reload Rails

I am building a job app with Rails. In my job 'new' page. I have a preview functionality where a user can click a 'preview button' to see how the job would look like when posted. On the preview page, the user can either post the job or click 'edit' to go back to the job new page.

The issue is that, when 'edit' is clicked the page reloads and all the data in the input fields get erased. I want to be able to preserve the data after the page reload so the user can edit the page without having to fill out forms from scratch. This is my controller action

def create
    @job = Job.new(job_params)
      if params[:previewButt] == "Preview"
        flash[:alert] = "This is a PREVIEW of your job posting".
        render :create
      elsif params[:createButt] == "Post Job"
        @job.save
        redirect_to root_path
      elsif params[:backButt] == "Make changes"
        render :new
      end
  end

In the 'preview' or 'create' view. I have this at the bottom of the page

<div class="col-md-9 text-center" style="margin-top: 110px;">
      <%= f.button :submit , name: "backButt", value: "Make changes" %>
      <%= f.button :submit , name: "createButt", value: "Post Job", class: "btn btn-success post-btn" %>
</div>

So ideally when the user clicked "Make changes" and the page reloads to render "new", the data in the form inputs should still be available.

mercredi 28 mars 2018

Ruby - convert string to date format

I want to convert a string like 20170319 to a date Format, and then to day of the year.

How to handle downtime of external app in rails code

in one of my rails application, I am using the gem which would generate a model by parsing some json from some external API. Now there is some downtime for those API and we are not able to access it which would also cause downtime for my application. I need to handle this situation programmatically so my application would not go down even though there is no data received from the corresponding API. I am trying to reproduce the same situation in my local environment and I am facing the following error. anyone can help me to overcome this issue

Web application could not be started

No such file or directory - dev20177.service-now.com/change_request.do?displayvalue=all&WSDL (Errno::ENOENT) /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/wasabi-3.2.3/lib/wasabi/resolver.rb:50:in read' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/wasabi-3.2.3/lib/wasabi/resolver.rb:50:inload_from_disc' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/wasabi-3.2.3/lib/wasabi/resolver.rb:34:in resolve' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/wasabi-3.2.3/lib/wasabi/document.rb:141:inxml' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/wasabi-3.2.3/lib/wasabi/document.rb:159:in parse' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/wasabi-3.2.3/lib/wasabi/document.rb:146:inparser' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/bundler/gems/sgtools_sncdws-3f0838938142/lib/service_now-dws/record.rb:46:in setup' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/bundler/gems/sgtools_sncdws-3f0838938142/lib/service_now-dws/plugin/config.rb:94:inblock in gen_models' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/bundler/gems/sgtools_sncdws-3f0838938142/lib/service_now-dws/plugin/config.rb:89:in each' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/bundler/gems/sgtools_sncdws-3f0838938142/lib/service_now-dws/plugin/config.rb:89:ingen_models' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/bundler/gems/sgtools_itsm-e753bf5bc899/lib/sgtools_itsm.rb:39:in gen_models' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/bundler/gems/sgtools_rails_itsm-bc3dcdf43e87/lib/sgtools/rails/itsm/engine.rb:25:inblock in ' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/railties-3.2.21/lib/rails/initializable.rb:30:in instance_exec' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/railties-3.2.21/lib/rails/initializable.rb:30:inrun' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/railties-3.2.21/lib/rails/initializable.rb:55:in block in run_initializers' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/railties-3.2.21/lib/rails/initializable.rb:54:ineach' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/railties-3.2.21/lib/rails/initializable.rb:54:in run_initializers' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/railties-3.2.21/lib/rails/application.rb:136:ininitialize!' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/railties-3.2.21/lib/rails/railtie/configurable.rb:30:in method_missing' /home/sunny.bogawat/work/viewpoint/config/environment.rb:9:in' config.ru:3:in require' config.ru:3:inblock in ' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/rack-1.4.7/lib/rack/builder.rb:51:in instance_eval' /home/sunny.bogawat/.rvm/gems/ruby-1.9.3-p374@vp2/gems/rack-1.4.7/lib/rack/builder.rb:51:ininitialize' config.ru:1:in new' config.ru:1:in' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:108:in eval' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:108:inpreload_app' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:153:in <module:App>' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:29:in' /usr/local/rvm/gems/ruby-1.9.3-p484@httpd24/gems/passenger-4.0.29/helper-scripts/rack-preloader.rb:28:in `' Application root

mardi 27 mars 2018

Select from foreign table with join and output JSON - Ruby on Rails 5

I have models Article and Language. Article has_many :languages and Language belongs_to: :article. I have method for selecting articles with their languages in Article model:

def self.per_page(limit, offset)
  left_joins(:languages)
  .limit(limit).offset(offset)
  .select('articles.id, articles.title, languages.language')
  .group(:id)
end

I call this method in articles_controller.rb:

def index
  limit = 40
  @articles = Article.per_page(limit, params[:offset])
  byebug
  render json: @articles
end

I have in articles one row with id=105 and three rows in languages table with article_id=105 The problem is that it selects only the first row per related article in languages table, but not all. Now JSON looks like:

{
    id: 105
    title: 'Some title',
    language: 'English'
}

I want to select all articles with all related to them languages and JSON output to be like :

{
    id: 105
    title: 'Some title',
    language: ['English', 'French', ...]
}

How can I do that ? It is not a problem if it is more than one request in the controller.

Error when tried to access params. undefined method `parameters for nil:NilClass

I am new to ruby and i am trying to move a controller concern into gem. So i have new repository.

When i stepped through the rspec and check for params i started getting the error in title. After looking online it say's params is an instance of action_controller so i added a application controller.

class ApplicationController < ActionController::Base
end

But i am still getting same error when tried to check params while stepping through concern.

I believe i should get params as <ActionController::Parameters ...something here...>

How can i fix this?

lundi 26 mars 2018

Rails 4 - ActiveAdmin layout is blank but application layout works for custom controller action

I have a Rails4 app with active_admin for admins only.i have been using it for quite a long time and has customised it to the way i want and it has always worked but now , it is this little weird issue which i am unable to resolve.

i have a custom action in my controller block inside my admin/hall.rb model, which is also getting executed as per the server logs which also includes the active_admin layout too BUT on the screen , i cannot see any layout and its just blank but when i use application layout explicitly in the controller block, it works.

ActiveAdmin.register Hall do

controller do


  ##explicitly add helper to be used by existing partials 
  helper ApplicationHelper 
  ###DO NOT WORK
  #layout 'active_admin' # <-- here
  ##THE WEIRD PART################
  layout 'application' , :except => [:activities] ===> this render the application layout perfectly which i dont want , as i need the active_admin layout
  layout 'active_admin' , :except => [:activities]  ==> also render the application layout...STRANGE
  layout 'active_admin' , :only => [:activities]  ==> render the application layout but with only icon and entire page is blank


  def activities
    @hall = MODEL.find params[:id]
    @activities = @hall.get_public_activity
    ##EVERYTHING BELOW THIS DO NOT WORK, I HAVE TRIED IT
    #render :activities, :layout => false
    #render :partial=>'admin/halls/activities', :layout => "active_admin"
    ##render "activities", layout: "active_admin"

  end 




       #######server logs
    Processing by Admin::HallsController#activities as HTML
    ...
    ...
    ....

       (1.7ms)  SELECT COUNT(*) FROM "activities" WHERE "activities"."trackable_id" = $1 AND ("activities"."owner_id" IS NOT NULL)  [["trackable_id", 1021]]
      PublicActivity::Activity Load (1.5ms)  SELECT  "activities".* FROM "activities" WHERE "activities"."trackable_id" = $1 AND ("activities"."owner_id" IS NOT NULL)  ORDER BY created_at desc LIMIT 50 OFFSET 0  [["trackable_id", 1021]]
      User Load (1.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 3]]
      Announcement Load (1.4ms)  SELECT  "announcements".* FROM "announcements" WHERE "announcements"."id" = $1 LIMIT 1  [["id", 1021]]
      Rendered public_activity/announcement/_create.html.erb (19.4ms)
      Rendered admin/halls/activities.html.erb within layouts/active_admin (27.4ms)
     ...
     ...

    Completed 200 OK in 681ms (Views: 368.8ms | ActiveRecord: 56.4ms | Elasticsearch: 0.0ms)

Can anyone help me to figure out what is going wrong here.

Thanks in advance.

SELECT list is not in GROUP BY clause and contains nonaggregated column - error with Ruby on Rails. 5

I have models Article and Language (tables articles and languages). Article has_many languages and Language belongs_to article. I want to select articles with their languages. I am using this in Article model:

def self.articles_per_page(limit, offset)
  joins("LEFT JOIN languages ON languages.article_id = articles.id")
  .select('articles.id, languages.language, COUNT(languages.id) as 
   all_languages')
  .limit(limit).offset(offset)
end

In the controller I have:

def get_per_page
  limit = 40
  render json: Article.articles_per_page(limit, params[:offset])
end

, but I am getting this MySQL error:

Mysql2::Error: Expression #10 of SELECT list is not in GROUP BY clause and contains nonaggregated column '.languages.language' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by: SELECT ....

If I add GROUP BY to the query:

def self.articles_per_page(limit, offset)
  joins("LEFT JOIN languages ON languages.article_id = articles.id")
  .select('articles.id, languages.language, COUNT(languages.id) as all_languages')
  .limit(limit).offset(offset)
  .group('articles.id, languages.language') 
end

The error is fixed, but then if I have 1 article in articles table and four languages (for the example) related to this article, this query returns four same articles.

Join tables with Ruby on Rails 5

I have models Article and Language (tables articles and languages). Article has_many languages and Language belongs_to article. I want to select articles with their languages. I am using this in Article model:

def self.articles_per_page(limit, offset)
  joins("LEFT JOIN languages ON languages.article_id = articles.id")
  .select('articles.id, languages.language, COUNT(languages.id) as all_languages')
  .limit(limit).offset(offset)
  .group('articles.id, languages.language')
end

In the articles_controller:

def get_per_page
  limit = 40
  render json: Article.articles_per_page(limit, params[:offset])
end

Then I make Ajax request to get JSON response with articles and their languages:

$.get(articlesUrl + '?offset=' + offset, function(article){
    $.each(article, function(index, performance){
        $('#articleTable').append(// DATA //);
    });
            offset = $('#articleTable').children('.articleRow').length;
        })

The problem is that, if I have 1 article in articles table and for the example 3 languages associated with this article in the languages table, it returns 3 rows with same article.

ActionController::RoutingError (uninitialized constant BaseController)

I create controller in app/controllers/v1/white_label_api

class Api::WhiteLabel::V1::BaseController < ApplicationController
end

and in other controllers I do

class Api::WhiteLabel::V1::CarMakeController < BaseController

But it gives an error uninitialized constant BaseController

dimanche 25 mars 2018

Time zone with day light savings in Ruby on Rails

I am working on an application where appointments were scheduled based on the availability of the user.

The user will choose their availability like "10:00 AM". I am going to store these availabilities in UTC in my database by converting it from users time zone to UTC. Say for example "10:00 AM" EST will get stored as "15:00" in UTC. So that I can show the availability of the user to the consumer by converting it from UTC to browsers time zone which is consumers timezone.

I am really confused of how to handle the day light savings while storing the availability of the user.

For example if the user chooses the time "10:00 AM" with daylight savings it will be stored as 14:00 in UTC and without day light savings it will be stored as 15:00.

For your information I am going to use the availability of the user based on day. i.e on Monday I will be available on "10:00 AM", "12:00 PM".

How can I handle this situation?

samedi 24 mars 2018

Rails 4 - Elasticsearch and searchkick NOT working as expected

I have a Rails4 app using elasticsearch and searchkick for a sitewide search page. i have configured the models and its associations using searchkick search_data, but its not working as per my requirement where user can search all venues by location,name,capacity,event(marriage,engagements etc) and food_type(veg/non-veg).Sharing the code below.

############### models/venue.rb ####################################


     ##columns of venue.rb
     ##=> Venue(id: integer, name: string, description: text,active: boolean, announcements_count: integer, comments_count: integer, pictures_count: integer, videos_count: integer, created_at: datetime, updated_at: datetime, capacity_in_persons: string, workflow_state: string) 

     ### associations 
     has_many :event_categories
     has_many :event_types, through: :event_categories
     has_one :address, :as=> :addressable, :dependent => :destroy   

     ###elasticsearch config starts here
    searchkick word_middle:["name^10", :slug,  :capacity_in_persons], locations: ["location"]

  def search_data
    {
      name: name, analyzer: 'english', #: :word_start, misspellings: false},
      capacity_in_persons: capacity_in_persons,
      food_type: food_type,
      slug: slug,
      ##has many event types
      event_type_name: event_types.map(&:name),
      ratings: ratings.map(&:stars),
      ##location: [self.address.latitude, self.address.longitude],
      location: [self.address.latitude, self.address.longitude],
      picture_url: pictures.select{|p| p == pictures.last}.map do |i|{

        original:  i.original_url 

        }
      end
    }
  end

##to eager load other associations
scope :search_import, -> { includes(:address, :event_types, :pricing_details, :ratings) }
after_save :reindex if try(:address).present?



  ###### controller action ##########
          @query = []
          @query << params[:venue_name] if params[:venue_name].present? 
          @query << params[:address] if params[:address].present?
          @query << params[:venue_capacity_in_persons] if params[:venue_capacity_in_persons].present?
          @query << params[:food_type] if params[:food_type].present?
          @query << params[:event_name] if params[:event_name].present?
          @query = @query.flatten.compact
          logger.tagged("SITE WIDE SEARCH"){ logger.info "**************SEARCH QUERY***#{@query}******************" }   
          ##TODO-add constraints to handle range for capacity in persons
          ###@halls = Hall.get_completed_halls_only.paginate(:page => params[:page]).search(@query).results
          ##@halls =  Hall.get_completed_halls_only.search(@query)
          @halls =  Hall.get_completed_halls_only.search params[:address],
                    where: {
                      capacity_in_persons: {lte: params[:venue_capacity_in_persons]},
                      food_type: params[:food_type],
                      event_type_name: params[:event_name]
                    }

Moreover, i have added changes to my address.rb to find venue nearby and i think it working fine but any suggestions are welcomed.address.rb is polymorphic and has address_1 attribute to store address coming from google dropdown along with geocoding from geocoder gem.

####################### models/address.rb #######################
###address belongs_to venue
searchkick locations: [:address_1] 

  ## call Address.reindex if this method is changed
  def search_data
    attributes.except("id").merge(
      address_1: {lat: latitude, lon: longitude},
      city: city,
      state: state,
      zipcode: zipcode  ##unless addressable_type == "Hall"
      )

  end

Kindly help me out as what changes do i need to make and where i am going wrong.

Thanks in advance

vendredi 23 mars 2018

Rails: how to create a list with conditional links

I am working on a RAILS application where I create a view which lists all available resources of a given model species.rb.

The view partial is:

<% i= @s
for species in @species %>
    <%= species.name %>, <%= species.author.surname %> <%= species.author.initial_name %>
<%  i -= 1
    end %>

Some of the resources species have an related article, others have only the name. I would like to loop through the partial and add a link only to the entries which have an associated article.

Something like: add link if species.article is present else just put species.name without link + loop through it for all entries.

How can I do this?

Ruby on Rails: uninitialized constant, NameError

Hello I am trying to solve a name error in a RAILS application. I am working on an interface which consists in a map with tiles associated to a certain number of projects.

I have the following models: area.rb

class Area < ActiveRecord::Base
  attr_accessible :map_file_name, :tile_file_name, :alt, ...

  has_many :species
  has_many :maps

end

map.rb,

class Map < ActiveRecord::Base
  attr_accessible :alt, :file_name, :detail, :area_id

  belongs_to :area
end

and specie.rb

class Specie < ActiveRecord::Base
  attr_accessible :area_id, :author_id, :name, :pwclass, :pwfamily, :txtlandscape, :txtpod, :map

  has_one :author
  belongs_to :area

end

When I try to call the resource in IRB or in a view I get the name error output. I changed specie to field and species to fields, and it works with the same configuration.

I checked and Ruby pluralises specie correctly to species.

How can I get specie to work?

UPDATE : backtrace

Started GET "/projects/show/1" for 127.0.0.1 at Fri Mar 23 13:02:07 +0100 2018
Connecting to database specified by database.yml
Processing by ProjectsController#show as HTML
  Parameters: {"id"=>"1"}
  [1m[36mArea Load (1.8ms)[0m  [1mSELECT 'areas'.* FROM 'areas' WHERE 'areas'.'id' = ? LIMIT 1[0m  [["id", "1"]]
  [1m[35mMap Load (0.4ms)[0m  SELECT 'maps'.* FROM 'maps' WHERE 'maps'.'area_id' = 1
  Rendered projects/show.html.erb (28.1ms)
Completed 500 Internal Server Error in 108ms

ActionView::Template::Error (uninitialized constant Area::Species):
    28:         end %>
    29: <% else %>
    30: <% end %>
    31: <% for specie in @area.species %>
    32: <div class="speciesmap">
    33:   <div id="tile_menu">
    34:     <a onclick="ArticleRequest('/article/show/area-07.html', 'ATLAS-06');"><img src="images/MAP/GUADALQUIVIR_MAP-BUTTONS-TILE-specie.svg" onMouseOver="this.src='images/MAP/estuario_area_136x85px-blck.svg'" onMouseOut="this.src='images/MAP/GUADALQUIVIR_MAP-BUTTONS-TILE-specie.svg'" alt="Specie"></a>
  app/views/projects/show.html.erb:31:in '_app_views_projects_show_html_erb__1608931551_2294133420'
  app/controllers/projects_controller.rb:22:in `show'


  Rendered /Users/xxx/.rvm/gems/ruby-1.8.7-p374@ccc/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.7ms)
  Rendered /Users/xxx/.rvm/gems/ruby-1.8.7-p374@ccc/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.6ms)
  Rendered /Users/xxx/.rvm/gems/ruby-1.8.7-p374@ccc/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (40.4ms)

Understanding histogram

OK I found this code of a histogram, I'm trying to understand how it works to be honest, an if there's an easier way to write out the code to do the same thing as its doing here but in a shorter way.

def histogram(array, start, stop, chart)
  (array.count {|array| array >= start and array <= stop}).to_s.rjust((chart))
end

array, stop, range, found, chart, start = [], 10, 1, 3, 2, 1

200.times do
  array.push(rand(1..100)).sort!
end

puts "  Range     #Found      Chart" "\n" " -------     ------    ------------------------------"
puts
print " 1 -  10      |#{histogram(array, start, stop, chart)}|     "
array.each do |counts|
  if counts > stop
    print "\n"
    start += 10
    stop += 10
    print "#{start.to_s.center(range)} "
    print "- #{stop.to_s.rjust(found)}      "
    print "|#{histogram(array, start, stop, chart)}|     *"
  else
    print "*"
  end
end

How to add new key-value pair in a Ruby Hash?

I've a hash called new_array which I've filled with key-value pairs received from a web hook notification. When that is done, I tried to enter a new key-value pair in the same hash called new_array. The problem is when I loop through the hash I've created, I only see the latest key-value pair I filled in the second step. Those I got from the webhook are all gone. This indicates that the key-value pair I entered later has overridden the old key-value pairs.

My goal in this case is to have all the key-value pairs in the hash new_array.

I also tried to create 2 individual hashes called new_array, new_array1 and merge them together like new_array.merge!(new_array1). That produced the same result. I hope someone can point me out the mistake I am making. The full code is below.

def test_method
      new_array = Hash.new
      @webhook[:note_attributes].each do |attribute|
         new_array[attribute[:name]] = attribute[:value]
      end

      if @webhook['source_name'] == 'shopify_draft_order'
         @gbp_rate = 1.41
         new_array["exchange_rate_gbp"] = @gbp_rate
      end

      new_array.each do |x|
         logger.debug "****************#{x}*****************"
      end

      new_array.to_json
   end

jeudi 22 mars 2018

DoubleRenderError (Render and/or redirect and adding 'and return' at the end of redirect_to or self.render

I have a messaging system every time I insert a message into the database. it insert duplicates im getting AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action). I tried to add and return at the end of redirect_to or self.render but it did not help. the problem it seems to be happening from the create method

# app/controllers/messages_controller.rb

class MessagesController < ApplicationController
   before_action :authenticate_user!
   before_action :set_conversation

  def index
    if current_user == @conversation.sender || current_user == 
      @conversation.recipient
      @other = current_user == @conversation.sender ? 
      @conversation.recipient : @conversation.sender
      @messages = @conversation.messages.order("created_at DESC")
    else
      redirect_to conversations_path, alert: "You don't have permission to view this."
    end
  end

  def create
    @message = @conversation.messages.new(message_params)
    @messages = @conversation.messages.order("created_at DESC")
    if @message.save
      ActionCable.server.broadcast "conversation_#{@conversation.id}", 
      message: render_message(@message)
      redirect_to conversation_messages_path(@conversation)
    end
  end

  private
  def render_message(message)
    self.render(partial: 'messages/message', locals: {message: message})
  end
  def set_conversation
    @conversation = Conversation.find(params[:conversation_id])
  end
  def message_params
    params.require(:message).permit(:context, :user_id)
  end
end

This is an image from my terminal

by removing

      ActionCable.server.broadcast "conversation_#{@conversation.id}", message: render_message(@message)
      redirect_to conversation_messages_path(@conversation)

it still insert duplicates messages

  def create
      @message = @conversation.messages.new(message_params)
      @messages = @conversation.messages.order("created_at DESC")
      @message.save
  end

this image of terminal before removing from the code

This an image from database show that it inserting duplicates

This new image from the terminal after i inserted

this is the view app/views/messages/index.html.erb

<div class="row">
  <div class="col-md-3 text-center">
   <%= image_tag avatar_url(@other), class: "img-circle avatar-medium" %>
   <strong><%= @other.fullname %></strong>
   <%= link_to "View Profile", @other, class: "btn btn-default" %>
 </div>
<div class="col-md-9">
 <div class="panel panel-default">
   <div class="panel-heading">
    Conversation with <%= @other.fullname %>
    <input id="conversation_id" type="hidden" value="<%= 
    @conversation.id %>">
    </div>
    <div class="panel-body">
    <div class="container text-center">
      <%= form_for [@conversation, @conversation.messages.new], remote: true do |f| %>
          <div class="form-group">
            <%= f.text_field :context, placeholder: "Add a personal message", class: "form-control" %>
          </div>
          <%= f.hidden_field :user_id, value: current_user.id %>
          <div>
            <%= f.submit "Send Message", class: "btn btn-normal" %>
          </div>
      <% end %>
    </div>
  </div>
</div>

<div id="chat">
  <%= render @messages %>
</div>

Ruby on rails Database setup using scaffold generator or Manually

I am new user to ruby on rails. I have some question please give the answer as early as possible

What is the Best way to Create a Database For Your Projects in Rails?

1.Scaffold generator

2.Manually Design Database​

mercredi 21 mars 2018

typeahead rails 3 autocomplete with user per request

The app is using typeahead and bootstrap 3 for, autocomplete function. but now we have so many records that , it is getting really slower.

   var substringMatcher = function(strs) {
        return function findMatches(q, cb) {
            var matches, substrRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(strs, function(i, str) {
                if (substrRegex.test(str)) {
                    // the typeahead jQuery plugin expects suggestions to a
                    // JavaScript object, refer to typeahead docs for more info
                    matches.push({ value: str });
                }
            });

            cb(matches);
        };
    };


$('.typeahead').each(function(elem) {
        $(elem).typeahead({
            hint: false,
            highlight: true,
            minLength: 3
        }, {
            displayKey: 'value',
            source: substringMatcher($(elem).data('source'))
        });
    });

these are javasxript parts of typeahead fuction used by the app

on the view side of the form

<div class="form-group">
        <label class="col-sm-2 control-label" for="typeahead_book">Title</label>
        <div class="col-sm-3">
        <input value="<%=@option.book.try(:title)%>" name="option[book_title]" type="text" class="form-control typeahead typeahead-remote-book" id="typeahead_book"  data-provide="typeahead" data-items="10" data-source='<%=@book_titles%>'>
          <p class="help-block"><small><%= $autocomplete_message %></small></p>
        </div>

i use a callback as

before_filter :get_autocomplete_lists, only: [:new, :edit]

def get_autocomplete_lists

    @book_titles = Rails.cache.fetch("booktitles", :force => true, expires_in: 10.minutes) do 
      Book.scoped.map(&:title)
    end


    @publisher_names = Rails.cache.fetch("publishernames", :force => true, expires_in: 10.minutes) do 
      Publisher.all.map(&:name)
    end


    @users_by_email_name = Rails.cache.fetch("users",  :force => true, expires_in: 7.days) do 
      User.scoped.map{|user| "#{user.email} - #{user.name}"}
    end 


    @country_names = Rails.cache.fetch("countrynames",  :force => true, expires_in: 7.days) do
      Country.all.map(&:first).sort
    end
    # @languages = LanguageList::COMMON_LANGUAGES.map(&:name)
    # @country_names = Anatolialit::Country::List.sort
    # 

    @languages = Rails.cache.fetch("languages",  :force => true, expires_in: 7.days) do 
      Anatolialit::Language::EnList.sort
    end

  end

on controller that generates source of the book , as @book_titles , THE APP IS WORKING NOW but i have to refactor the code for performance issues.Because after 10k record @book_titles is very big.


THAN WHAT I DID i created a new controller action on application controller
def book_titles
     searchterm = (params[:title])
     books =Book.any_of({ :title => /.*#{searchterm}.*/ })
     respond_to do |format|
      format.json { render json: books.map(&:title)  }
     end
  end


and i defined a route to use as application controller as an api service

get 'booktitles/:title' => 'application#book_titles', format: :json

now when i use a localhost:3000/booktitles/the it brings me as a json data all the books that indicates 'the' in the title. I think everything Until here is ok. about refactoring.


but when i use this code below for userside per request for sourcing typeahead
$(document).ready(function() {
  $('.typeahead-remote-book').typeahead({
      source: function (query, process) {
          return $.get('/booktitles', { query: query }, function (data) {
              return typeahead.process(data);
          });
      }
  });
});


and i changed the view part of the form to

<div class="form-group">
        <label class="col-sm-2 control-label" for="typeahead_book">Title</label>
        <div class="col-sm-3">
        <input value="<%=@option.book.try(:title)%>" name="option[book_title]" type="text" class="form-control typeahead typeahead-remote-book" id="typeahead_book"  data-provide="typeahead" data-items="10" >
          <p class="help-block"><small><%= $autocomplete_message %></small></p>
        </div>
      </div>

*I do not know what is wrong with the situation , but it does not work *

could u please help me ? about solving the problem. Thanks for your kind help.. best regards.

mardi 20 mars 2018

How to save to Active Record using two different timezones in the same transaction

I have a model which contains two different DateTime properties. One of them needs to be based in one timezone and the other needs to be based in a different timezone, before saving.

I need to tell Rails which timezones are the starting point for each of these properties before it converts them to UTC. Can I do that in the same transaction?

My idea at this point is to set the timezones in different transactions, which I'd like to avoid if possible.

How to dump schema of all users defined in database.yml file

My database.yml looks like

development: &development
  adapter: oracle_enhanced
  database: some_db
  username: admin
  password: password

temp_development:
  <<: *development
  username: another_user
  password: another_password

auth_development:
  <<: *development
  username: authority
  password: authority

When I run rake db:schema:dump it will dump all the tables created by user admin into schema.rb, how can I dump table created in another schema or created by other users like another_user and authority in schema.rb

vendredi 16 mars 2018

undefined method `instantiate' on Rails Polymorphic Associations

I am using rails 3.2.12 ruby 1.9.3 and mongoid 3.1.7 as orm/driver for mongo 2.6

I have an address class which can be used in multiple models

class Address < ApplicationRecord
  embedded_in :addressable, polymorphic: true
end

class Customer < ApplicationRecord
  embeds_one :address, autobuild: true, as: :addressable
end

class Invoice < ApplicationRecord
  embeds_one :address, autobuild: true, as: :addressable
end

Not every time but on random I am getting an error on my view

Started GET "/customers/asdadsdsdsdsds?sid=abcdfsd" for ------ at 2018-03-16 10:38:11 -0400
Processing by CustomersController#show as HTML
  Parameters: {"sid"=>"xyz", "id"=>"abc"}
  Rendered customers/show.html.haml within layouts/application (2.5ms)
Completed 500 Internal Server Error in 439ms
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/_request.text.erb (0.4ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.1ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/_session.text.erb (0.6ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.1ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/_environment.text.erb (9.0ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.1ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/_backtrace.text.erb (0.2ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.1ms)
  Rendered /usr/local/rvm/gems/ruby-1.9.3-p547/gems/exception_notification-3.0.1/lib/exception_notifier/views/exception_notifier/exception_notification.text.erb (22.0ms)

Sent mail to me (60ms)

ActionView::Template::Error (undefined method `instantiate' for Address:Class):
    40: 
    41: .dl-horizontal
    42:   %dt Address
    43:   %dd= customer.address
    44: 
    45: .dl-horizontal

  app/views/customers/show.html.haml:43:in `_app_views_customers_show_html_haml__4324924039767281630_61736740'

more from backtrace

-------------------------------
Backtrace:
-------------------------------

  mongoid (3.1.7) lib/mongoid/factory.rb:40:in `from_db'
  mongoid (3.1.7) lib/mongoid/relations/builders/embedded/one.rb:21:in `build'
  mongoid (3.1.7) lib/mongoid/relations/accessors.rb:43:in `create_relation'
  mongoid (3.1.7) lib/mongoid/relations/accessors.rb:26:in `__build__'
  mongoid (3.1.7) lib/mongoid/relations/accessors.rb:116:in `block (2 levels) in get_relation'
  mongoid (3.1.7) lib/mongoid/threaded/lifecycle.rb:125:in `_loading'
  mongoid (3.1.7) lib/mongoid/relations/accessors.rb:115:in `block in get_relation'
  mongoid (3.1.7) lib/mongoid/threaded/lifecycle.rb:84:in `_building'
  mongoid (3.1.7) lib/mongoid/relations/accessors.rb:114:in `get_relation'
  mongoid (3.1.7) lib/mongoid/relations/accessors.rb:223:in `block in getter'
  app/views/customers/show.html.haml:43:in `_app_views_customers_show_html_haml___1573920893515992280_74752380'
  actionpack (3.2.12) lib/action_view/template.rb:145:in `block in render'

Add tag to input

Let's say I have such an input:

f.text_field :name 

How can I add this tag to it: data-hj-whitelist

So that It looks something like:

<input type="text" name="name" data-hj-whitelist/>

Thanks

Routing Error uninitialized constant controller

Im am trying to learn Ruby on rails and i keep getting this error.

My controller is

class Clasa9Controller < ApplicationController
  def multimi
  end

  def progresii
  end

  def functii
  end

  def vectori
  end

  def trigonometrie
  end

  def geometrie
  end
end

clasa9.html.erb

 <button class="btn"><%= link_to "", multimi_path %></button>

rails routes:

multimi GET    /clasa_9/multimi(.:format)           clasa_9#multimi
               progresii GET    /clasa_9/progresii(.:format)         clasa_9#progresii
                 functii GET    /clasa_9/functii(.:format)           clasa_9#functii
                 vectori GET    /clasa_9/vectori(.:format)           clasa_9#vectori
           trigonometrie GET    /clasa_9/trigonometrie(.:format)     clasa_9#trigonometrie
               geometrie GET    /clasa_9/geometrie(.:format)         clasa_9#geometrie

and routes.rb

 get 'clasa_9/multimi', to:"clasa_9#multimi", as:"multimi"

  get 'clasa_9/progresii', to:"clasa_9#progresii", as:"progresii"

  get 'clasa_9/functii', to:"clasa_9#functii", as:"functii"

  get 'clasa_9/vectori', to:"clasa_9#vectori", as:"vectori"

  get 'clasa_9/trigonometrie',  to:"clasa_9#trigonometrie", as:"trigonometrie"

  get 'clasa_9/geometrie',  to:"clasa_9#geometrie", as:"geometrie"

  devise_for :users

  get 'pages/home'

  get 'pages/clasa9'

  get 'pages/clasa10'

  get 'pages/clasa11'

  get 'pages/clasa12'

  get 'pages/about'

  root 'pages#home'

and im am getting

Routing Error uninitialized constant Clasa9Controller

i tried to solve this by looking up what is already posted here but i just cant solve it.. i dont understand what i should change.

Get the next Object Id before create the object for a Model Rails

I have a Model I need to get the next record id which is going to be create before create that object in my model like:

MyModel.last.id #=> 10
MyModel.last.destroy
MyModel.last.id #=> 9, so (Model.last.id + 1) would be 10... but...
MyModel.create  #=> 11, my next id was actually 11

Can you please suggest a better way to solve my problem?

Thanks

jeudi 15 mars 2018

RSpec: How to run the feature specs after all other specs

We have a rather complex integration spec setup with capybara and chrome. This leads to slow feature specs.

It would be nice if the feature specs would be executed after all other specs. Because it takes rather long time for a integration test to "boot" and find a bug which a simple request or unit test would have found way faster before.

But all tests should be ordered randomly by seed like before. And it should still work with simplecov.

To find out uniq values from an array of hashes based on an input hash

a = [
  { :color => "blue", :name => "wind" },
  { :color => "red", :name => "fire" },
  { :color => "white", :name => "wind" },
  { :color => "yellow", :name => "wind" },
  { :color => "green", :name => nil },
  { :color => "white", :name => "snow" }
]

I have another hash
b = { blue: 'blue', white: 'white', red: 'red', green: 'green' }

The result I need is:

['wind', 'fire']

# To find out uniq names based on the input hash.

What I tried:

names = a.map{ |i| {i[:color], i[:name]} }.delete_if { |key, value| value.nil? }
resultant_names = []
b_values = b.values

b_values.each do |c|
  if names[c]
    resultant_names << names[c]
  end
end
resultant_names.uniq

Need a better approach please. This goes with too many loops.

mardi 13 mars 2018

Rails 5 testing controller show action, missing required keys: [:id]

i'm using rails 5.1.5, and default testing library, so when i try to test my show action in posts contoller, i get an error:

Error:
PostsControllerTest#test_should_show_post:
ActionController::UrlGenerationError: No route matches
{:action=>"show",   :controller=>"posts"}, missing required keys: [:id]

here is My posts_controller_test.rb

require 'test_helper'

class PostsControllerTest < ActionDispatch::IntegrationTest

test "should get index" do
  get posts_url, params: { keywords: "" }
  assert_response :success
end

test "should show post" do
  post = posts(:post)
  get post_url, params: {id: post.id}
  assert_response :success
end

end

Here is my post fixture file posts.yml

post:
  title: testpost
  body: lorem ipsum
  user: tom

routes.rb

Rails.application.routes.draw do
  root "posts#index"
  devise_for :users
  resources :posts do
    resources :comments
  end
  resources :users, except: [:create, :new]
  resources :tags, only: [:show, :create]
end

posts_controller.rb

class PostsController < ApplicationController

  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]
  before_action :check_owner, only: [:destroy, :edit, :update]


  def index
    @posts = Post.search(params[:keywords]).uniq
  end

  def show
    #set_post
  end

  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    # link the post to user that logged in atm
    @post.user = current_user
    if @post.save
      # redirect to created post and show flash
      redirect_to @post, success: "Post successfully created !"
    else
      render :new
    end
  end

  def edit
    #set_post
    #check_owner
  end

  def update
    #set_post
    #check_owner
    if @post.update_attributes(post_params)
      # redirect to updated post and show flash
      redirect_to @post, success: "Post successfully updated !"
    else
      render :edit
    end
  end

  def destroy
    #set_post
    #check_owner
    @post.destroy
    # redirect to root and show flash
    redirect_to posts_path, success: "Post successfully deleted !"
  end


  private

    def set_post
      @post = Post.find(params[:id])
    end

    # strong params
    def post_params
      params.require(:post).permit(:title, :body, :image, :image_cache, :status, :adress, :current_tags)
    end

    def check_owner
      #check if current user is owner of the post
      redirect_to @post, alert: "You are not the owner of this post" unless current_user == @post.user || current_user.admin?
    end
end

and finally my test console

Running via Spring preloader in process 3663
Loading test environment (Rails 5.1.5)
2.4.1 :001 > User.all
User Load (0.3ms)  SELECT  "users".* FROM "users" LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<User id: 1038054164, email: "test@example.org", created_at: "2018-03-13 16:49:29", updated_at: "2018-03-13   16:49:29", username: "Tomaskoz", avatar: nil, role: "user">]>
2.4.1 :002 > Post.all
Post Load (0.3ms)  SELECT  "posts".* FROM "posts" LIMIT $1  [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Post id: 445279374, title: "testpost",  body: "lorem ipsum", created_at: "2018-03-13 16:49:29", updated_at: "2018-03-13 16:49:29", image: nil, user_id: 1038054164, status: true, adress:  nil>]>
2.4.1 :003 > 

My should get index test goes fine, but the second one doesn't, i've tried to solve the problem by myself for 2 days, but it's not seems to be possible, please help me thank in advance !

InstallError: nokogiri requires Ruby version >= 2.1.0

My current rails application has been built on ruby 1.9.3 and rails 3. I am doing bundle install one of the rails engines and I am received following error

Gem::InstallError: nokogiri requires Ruby version >= 2.1.0. An error occurred while installing nokogiri (1.8.2), and Bundler cannot continue. Make sure that gem install nokogiri -v '1.8.2' succeeds before bundling.

How I can get rid of this issue without updating ruby version.

How to pass argument to subject in rspec

I have one subject block which i want to reuse in varioius places.

subject(:stubbed_data) do

expect(response.body).to eq(dynamic_var)

end 

The dynamic_var variable will be different for different test cases. is there any way to call subbed_data subject with arguments so that i can have dynamic value for dynamic_var variable.

How to print the user password in rails view

In my controller

@user = User.last

In my view

<%= @user.password.inspect %> it returns nil value. but if i am using <%= @user.encrypted_password.inspect %> it shows "$2a$11$LXD0UDB3kvwxqG/w/0icGuy6iXEOFZ264ushzSi6LfXSdAitwPmNO" but i need to print the password not the encrypted password. so help me guys.

lundi 12 mars 2018

actions in same model , restricting some functions in common

In a rails application , there is an action in a model which used by other actions in the same model ... but in this common action some functions such as ' func1 func 2' must not be used by some of the actions refferred,

is there an easy way of implementing this ?

Ruby on Rails: User Interface issue in f.association as: :check_boxes

First thing is that my cursor shows clickable option on label, Second when I clicked on check box UI get disturb. Please find attached snapshot of User Interface. Thanks for any hint.

Here is my code

=f.association :user_practices, required: true,as: :check_boxes,collection: remove_guest_role(@practice.indoor, @user.persisted?,@user_role), :label => false,:selected => @current_roles

User interface snapshot of check boxes

dimanche 11 mars 2018

How do you create and manage account in Ruby on Rails?

I want to create an ecommerce website but I have one dilemma is that I do not know how to create account in Ruby on Rails? If anyone knows any tutorials, documentations, or code that can help me learn how to handle accounts.

samedi 10 mars 2018

rqrcode on ruby rails

I tried the example in this website:

https://richonrails.com/articles/generating-qr-codes-in-your-ruby-on-rails-application

to generate a qr code. there seems to be a problem with the 'require rqr-code' line which I have in the config/environment.rb file.

I checked that the gem is installed and it is. I removed the line 'require rqr-code' from the config/environment.rb file and then I get error 'uninitialized constant QrCodesController::RQRCode' at the controller:

 def create
    @qr = RQRCode::QRCode.new(qr_code_params[:text],size:4)
 end

when I re-add the line 'require rqr-code' and restart the rails server, I get the error - 'require': cannot load such file - rqrcode (LoadError).

I have been at this for some hours trying to figure out what it is. Thanks.

vendredi 9 mars 2018

Rails - Active Record validations and mark_for_destruction

I'm running on Rails 3.2.22.5 and I can't find any documentation that states whether or not child objects (that have mark_for_destruction set to true) will still have Active Record validations run against them.

Example:

class Parent < ActiveRecord::Base
  has_many :children
  validates_presence_of :children

class Child < ActiveRecord::Base
  belongs_to :parent


 parent = Parent.new
 parent.children << Child.new
 parent.children.first.mark_for_destruction
 parent.save!

I would expect the validates_presence_of to fail, since the child is marked_for_destruction. However, I have seen this validation pass in has_and_belongs_to_many relationships.

This was apparently a bug in Rails at one point, but I am not clear on what the expectation actually is since it's not documented. https://github.com/rails/rails/issues/6812

Unicorn restart error Failed to create timer thread (errno: 11)

I am trying to restart unicorn service on my rails app but getting this error in logs. Please help.

I, [2018-03-09T09:27:10.028799 #16454]  INFO -- : listening on addr=/tmp/unicorn.sanddollar.sock fd=10
I, [2018-03-09T09:27:10.029139 #16454]  INFO -- : worker=0 spawning...
I, [2018-03-09T09:27:10.031123 #16454]  INFO -- : worker=1 spawning...
I, [2018-03-09T09:27:10.031790 #16457]  INFO -- : worker=0 spawned pid=16457
I, [2018-03-09T09:27:10.031984 #16457]  INFO -- : Refreshing Gem list
I, [2018-03-09T09:27:10.032334 #16454]  INFO -- : worker=2 spawning...
[FATAL] Failed to create timer thread (errno: 11)
I, [2018-03-09T09:27:10.036780 #16460]  INFO -- : worker=1 spawned pid=16460
I, [2018-03-09T09:27:10.037023 #16460]  INFO -- : Refreshing Gem list
[FATAL] Failed to create timer thread (errno: 11)
I, [2018-03-09T09:27:30.690995 #16460]  INFO -- : worker=1 ready
I, [2018-03-09T09:27:30.852442 #16457]  INFO -- : worker=0 ready

Ruby Watir - How do I call Page Objects in Test scripts?

I am wondering how I call page objects from the page object class into my test class from a different directory? New to ruby! In java I would just import the class at the top of the class file and that would allow me to access the methods and objects from that class file in a different folder/package. My Directory structure is like so below:

enter image description here

I want to be able to access the page objects in the page object class to use in my A_Test class. How do I achieve this?

page_object.rb code:

require 'rubygems'
require 'cucumber'
require 'watir'
require 'page-object'
require 'test/unit/assertions'
include Test::Unit::Assertions

class screen
    include PageObject
    radio_button(:yes, id: '')
    radio_button(:no, id: '')
    button(:next_button, id: '')
    link(:back, :text => "")
end 

A_test.rb code:

require 'rubygems'
require 'cucumber'
require 'page-object'
require 'watir'
require 'date'

Given(/^$/) do |no|

   screen.next_button.click

end 

jeudi 8 mars 2018

How to pass keyword parameter to ruby rufus scheduler?

I am learning about redmine.

I am trying to receive email with rufus scheduler as explain here http://www.redmine.org/projects/redmine/wiki/RedmineReceivingEmails#Schedule-email-receiving-with-Rufus-Scheduler

I don't understand how to pass the parameter to scheduler like project, traker, allow_override etc.

Currently I am passing like this

require 'rubygems'
require 'rake'
require 'rufus-scheduler'

load File.join(Rails.root, 'Rakefile')

load File.join(Rails.root, 'Rakefile')

ENV['host']='imap-mail.outlook.com'
ENV['port']='993'
ENV['ssl']='true'
ENV['username']='username@domain.in'
ENV['password']='*********'

ENV['project'] = 'myproject'
ENV['tracker']='bug'
ENV['allow_override']='all'

scheduler = Rufus::Scheduler.new
Check emails every 1 mins
scheduler.interval '1m' do
task = Rake.application['redmine:email:receive_imap']
task.reenable
task.invoke
end

This is working fine but I don't pass these parameters as the ENVIRONMENT variable. Because It affects other views.

I was trying to pass this way, task = Rake.application['redmine:email:receive_imap project=myproject tracker=bug allow_override=all'] But I didn't work.

Can someone tell me the correct way to pass these parms to receive_imap task? Any help would be appreciated. Thanks.

Ruby on Rails searching with two strings

I have a model projects. And I have a search form with many search bars. What I want is (within the oder searches) a search bar where you can type in two strings. If you want to find all projects regarding "Graphics Card" and "China" you should be able to type in something like graph chin and all these records will be displayed.

In the Projct model I have this

def self.google(var1, var2)
    where("brief_title LIKE ? and country LIKE ?", "%#{var1}%", "%#{var2}%")
end

In the ProjectsController I have a bunch of code and tryed the following but it doesn't work (look for google)

bunch of other code

else
   @projects = Project.select_stuff(params[:stuff_id]).select_x(params[:x_id]).search(params[:search]).google(params[:var1], params[:var2]).paginate(:per_page => 25, :page => params[:page])
end

Has someone a clue?

Thank you in advance

page object class file at runtime and create an instance of the object in the test_class file?

I have a Directory structure which is below. I want to be able to access the page object class file at runtime and create an instance of the object in the test_class file. How do I do this?

Features - dir

 Page_Objects - sub dir
  Object Class - file

 Step_Definitions - sub dir
  test_class - file

At the moment what I Have is below:

Features - dir
  Step_Definitions - sub dir
  Object Class - holds objects
  test_class - test code
  Create_All_Objects Class by using: @name = classNameInsideObjectClassFile.new(@browser)

It seems to work as all the files are in the same directory as each other, however, for readability and maintainability, I want to put all the page Object classes in there own directory away from the test classes. New to ruby here..

mercredi 7 mars 2018

rails string substitution or similar solution in controller

I'm building a site with users in all 50 states. We need to display information for each user that is specific to their situation, e.g., the number of events they completed in that state. Each state's view (a partial) displays state-specific information and, therefore, relies upon state-specific calculations in a state-specific model. We'd like to do something similar to this:

@#{user.state} = #{user.state.capitalize}.new(current_user)

in the users_controller instead of

@illinois = Illinois.new(current_user) if (@user.state == 'illinois')
.... [and the remaining 49 states]
@wisconsin = Wisconsin.new(current_user) if (@user.state == 'wisconsin')

to trigger the Illinois.rb model and, in turn, drive the view defined in the users_controller by

def user_state_view
  @user = current_user
  @events = Event.all
  @illinois = Illinois.new(current_user) if (@user.state == 'illinois')
end

I'm struggling to find a better way to do this / refactor it. Thanks!

how to integrate angular 4 with rails 3?

I have developed an application with ruby on rails 3 for five years. The application recently has many users working in, it doesn't have api and the stylesheet and design are printed with the backend. I have developed some applications with angular 4 and I love it. I would like to integrate my app made with rails to angular 4 but I don't want to redesign all the app.

Loading Relations

Goal: I would like to include all of a customers medical conditions as an array in the result of a customer.

for:

cust = Customer.includes(:conditions).find(1)

expected result:

#<Customer id: 1, first_name: "John", last_name: "Doe", conditions [...]>

actual result:

#<Customer id: 1, first_name: "John", last_name: "Doe">

code:

I have 2 classes and a 3rd join class (ConditionsCustomer).

class Customer < ApplicationRecord
    has_many :conditions_customers
    has_many :conditions, through: :conditions_customers
end

#join table. Contains 2 foreign_keys (customer_id, condition_id)
class ConditionsCustomer < ApplicationRecord
  belongs_to :customer
  belongs_to :condition
end

class Condition < ApplicationRecord
  has_many :conditions_customers
  has_many :customers, through: :conditions_customers
end

What's interesting is that I see 3 select queries getting fired (customer, join table and medical conditions table) but then unfortunately the customer returns without the medical conditions.

I've also tried using a join but I get an array of same customer over and over again.

Is there an easy way to do this with ActiveRecord? I would prefer not having to merge the record manually.

How to use "unless" for Array in Ruby?

        if lineItemQuantities
          lineItemQuantities.each do |lineItemQuantity|
            if lineItemQuantity["lineItemQuantityType"] == "Accepted"
              outstanding_value  = outstanding_value + lineItemQuantity["quantity"]*(lineItemQuantity["unitPrice"] + lineItemQuantity["unitTax"])
            end
          end
        end

How to use unless in my above code? I tried using it by referring how to not iterate nil array ruby? But was not able to do that.

lundi 5 mars 2018

Gitlab API, how to get files from all branches of a project with ruby

i can list all the files/directories of a project from Gitlab. But now i want to list all the files/directories from all existing branches of a project.

samedi 3 mars 2018

PostgreSQL ActiveRecord Query Optimization

I'm new to RoR and I need a query that returns the same instances as the following definition of queue :

@all = User.all
@membersOfActivity = User.where(id: User.joins(:memberships).where("activity_id = ?", session[:current_activity_id])) 
@usersIAlreadyLiked = User.where(id: User.joins(:likes).where("activity_id = ? AND activity_likes_user IS NOT NULL", session[:current_activity_id])) 
@notWanted = @membersOfActivity + @usersIAlreadyLiked 
@queue = @all - @notWanted

However, I understand how inefficient the query I just wrote is for it downloads all the Users first to then select the complement. Do you have any idea on how to make it more efficient and directly select the complement of @notWanted? I tried several queries but none of those worked. If you think you have a better solutions please let me know! Thanks!

vendredi 2 mars 2018

Active Admin with join table relation

I am configuring Active Admin. Everything is running apart from a join table, which connects the magazine resource with the keyword resource. One magazine is defined by multiple keywords and a keyword can define multiple magazines.

I have two models:

### models/magazine.rb

class Magazine < ActiveRecord::Base
    attr_accessible :colour, :cover_alt, :description, :number, :short, :title_id

    has_and_belongs_to_many :keywords, :join_table => "magazines_keywords" 
    belongs_to :title, :class_name => "Keyword", :foreign_key => "title_id"
end


### models/keywords.rb

class Keyword < ActiveRecord::Base
  attr_accessible :word, :description

  has_and_belongs_to_many :magazines, :join_table => "magazines_keywords"
end

And a join table:

### models/magazines_keyword.rb
class MagazinesKeyword < ActiveRecord::Base
  attr_accessible :magazine_id, :keyword_id

  belongs_to :magazine
  belongs_to :keyword
end

This setting works for the views of my rails app, and I have the index and show section of my AA magazine resource working, but the form (for new and edit) does not work:

ActiveAdmin.register Magazine do
    menu :priority => 1

    form do |f|
        f.semantic_errors *f.object.errors.keys
        f.inputs "Magazine Details" do
            f.input :title_id, :label => 'Title', :as => :select, :collection => Keyword.all.map{ |u| ["#{u.word.capitalize}", u.id] }
            f.inputs :magazines_keywords do
                f.has_many : magazines_keywords do |s|
                    s.input :keyword, :as => :select, :multiple => true, :collection => MagazinesKeyword.all.map { |u| ["#{u.keyword.word.capitalize}", u.id] }
                end
            end
        end
        f.actions
    end

    show do
        panel "Magazine Details" do
            attributes_table_for magazine do
                row "Keywords", :keyword do |m|
                    m.keywords.map { |d| d.word }.join(", ").html_safe
                end
            end
        end
        active_admin_comments
    end
end

When running the app i get NoMethodError in Admin/magazines#edit

Where /active_admin/resource/edit.html.arb line #1 raises undefined method 'klass' for nil:NilClass

I can display all the keywords in the form section with:

f.input :magazines_keywords, :as => :check_boxes, :multiple => true, :collection => MagazinesKeyword.all.map{ |u| ["#{u.keyword.word.capitalize}", u.id] }

But when I try to write them it does not work. Editing the values does not work either.

Where am I missing something? How can I get this working?

Active Admin Editor not running

I am trying to include an editor in an Active Admin setting. I am able to bundle install every version of it up to 1.0.6, but when I run rails s and try to access the admin page I get the following error:

Sass::SyntaxError in Admin/keywords#index

Showing /Users/xxxxx/.rvm/gems/xxxxx/gems/activeadmin-0.6.0/app/views/active_admin/resource/index.html.arb where line #1 raised:

File to import not found or unreadable: ../functions/linear-gradient.
Load path: Sass::Rails::Importer(/Users/xxxxx/.rvm/gems/xxxxx/gems/active_admin_editor-1.0.5/app/assets/stylesheets/active_admin/editor.css.scss)
  (in /Users/xxxxx/.rvm/gems/xxxxx/gems/active_admin_editor-1.0.5/app/assets/stylesheets/active_admin/editor.css.scss)



ActionView::Template::Error (File to import not found or unreadable: ../functions/linear-gradient.
Load path: Sass::Rails::Importer(/Users/xxxx/.rvm/gems/xxxx/gems/active_admin_editor-1.0.5/app/assets/stylesheets/active_admin/editor.css.scss)
  (in /Users/xxxx/.rvm/gems/xxxx/gems/active_admin_editor-1.0.5/app/assets/stylesheets/active_admin/editor.css.scss)):
    1: insert_tag renderer_for(:index)
  bourbon (1.0.4) app/assets/stylesheets/css3/_background-image.scss:5
  bourbon (1.0.4) app/assets/stylesheets/_bourbon.scss:9
  activeadmin (0.6.0) app/assets/stylesheets/active_admin/mixins/_all.css.scss:11
  activeadmin (0.6.0) app/assets/stylesheets/active_admin/_mixins.css.scss:1
  active_admin_editor (1.0.5) app/assets/stylesheets/active_admin/editor.css.scss:1
  sass (3.1.10) lib/sass/./sass/tree/import_node.rb:64:in `import'
  sass (3.1.10) lib/sass/./sass/tree/import_node.rb:25:in `imported_file'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:147:in `visit_import'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `send'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:18:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `visit_import'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `map'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `visit_import'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `send'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:18:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `visit_import'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `map'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `visit_import'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `send'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:18:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `visit_import'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `map'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:144:in `visit_import'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `send'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:18:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:53:in `visit_children'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:53:in `map'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:53:in `visit_children'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:27:in `visit_children'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:39:in `with_environment'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:26:in `visit_children'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:47:in `visit_root'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `send'
  sass (3.1.10) lib/sass/./sass/tree/visitors/base.rb:37:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:18:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:7:in `send'
  sass (3.1.10) lib/sass/./sass/tree/visitors/perform.rb:7:in `visit'
  sass (3.1.10) lib/sass/./sass/tree/root_node.rb:20:in `render'
  sass (3.1.10) lib/sass/./sass/engine.rb:300:in `_render'
  sass (3.1.10) lib/sass/./sass/engine.rb:247:in `render'
  sass-rails (3.2.6) lib/sass/rails/template_handlers.rb:106:in `evaluate'
  tilt (1.4.1) lib/tilt/template.rb:103:in `render'
  sprockets (2.1.4) lib/sprockets/context.rb:177:in `evaluate'
  sprockets (2.1.4) lib/sprockets/context.rb:174:in `each'
  sprockets (2.1.4) lib/sprockets/context.rb:174:in `evaluate'
  sprockets (2.1.4) lib/sprockets/processed_asset.rb:12:in `initialize'
  sprockets (2.1.4) lib/sprockets/base.rb:241:in `new'
  sprockets (2.1.4) lib/sprockets/base.rb:241:in `build_asset'
  sprockets (2.1.4) lib/sprockets/base.rb:262:in `circular_call_protection'
  sprockets (2.1.4) lib/sprockets/base.rb:240:in `build_asset'
  sprockets (2.1.4) lib/sprockets/index.rb:89:in `build_asset'
  sprockets (2.1.4) lib/sprockets/caching.rb:19:in `cache_asset'
  sprockets (2.1.4) lib/sprockets/index.rb:88:in `build_asset'
  sprockets (2.1.4) lib/sprockets/base.rb:163:in `find_asset'
  sprockets (2.1.4) lib/sprockets/index.rb:56:in `find_asset'
  sprockets (2.1.4) lib/sprockets/bundled_asset.rb:16:in `initialize'
  sprockets (2.1.4) lib/sprockets/base.rb:244:in `new'
  sprockets (2.1.4) lib/sprockets/base.rb:244:in `build_asset'
  sprockets (2.1.4) lib/sprockets/index.rb:89:in `build_asset'
  sprockets (2.1.4) lib/sprockets/caching.rb:19:in `cache_asset'
  sprockets (2.1.4) lib/sprockets/index.rb:88:in `build_asset'
  sprockets (2.1.4) lib/sprockets/base.rb:163:in `find_asset'
  sprockets (2.1.4) lib/sprockets/index.rb:56:in `find_asset'
  sprockets (2.1.4) lib/sprockets/environment.rb:74:in `find_asset'
  sprockets (2.1.4) lib/sprockets/base.rb:171:in `[]'
  actionpack (3.2.5) lib/sprockets/helpers/rails_helper.rb:126:in `asset_for'
  actionpack (3.2.5) lib/sprockets/helpers/rails_helper.rb:44:in `stylesheet_link_tag'
  actionpack (3.2.5) lib/sprockets/helpers/rails_helper.rb:43:in `collect'
  actionpack (3.2.5) lib/sprockets/helpers/rails_helper.rb:43:in `stylesheet_link_tag'
  arbre (1.0.1) lib/arbre/element.rb:175:in `send'
  arbre (1.0.1) lib/arbre/element.rb:175:in `method_missing'
  activeadmin (0.6.0) lib/active_admin/views/pages/base.rb:27:in `build_active_admin_head'
  activeadmin (0.6.0) lib/active_admin/views/pages/base.rb:26:in `each'
  activeadmin (0.6.0) lib/active_admin/views/pages/base.rb:26:in `build_active_admin_head'
  arbre (1.0.1) lib/arbre/context.rb:92:in `with_current_arbre_element'
  arbre (1.0.1) lib/arbre/element/builder_methods.rb:49:in `within'
  activeadmin (0.6.0) lib/active_admin/views/pages/base.rb:24:in `build_active_admin_head'
  activeadmin (0.6.0) lib/active_admin/views/pages/base.rb:9:in `build'
  arbre (1.0.1) lib/arbre/element/builder_methods.rb:30:in `build_tag'
  arbre (1.0.1) lib/arbre/context.rb:92:in `with_current_arbre_element'
  arbre (1.0.1) lib/arbre/element/builder_methods.rb:26:in `build_tag'
  arbre (1.0.1) lib/arbre/element/builder_methods.rb:39:in `insert_tag'
  activeadmin (0.6.0) app/views/active_admin/resource/index.html.arb:1:in `___sers__tephan__rvm_gems_ruby_______p____saftzine_gems_activeadmin_______app_views_active_admin_resource_index_html_arb___381976998_2302642480'
  arbre (1.0.1) lib/arbre/context.rb:45:in `instance_eval'
  arbre (1.0.1) lib/arbre/context.rb:45:in `initialize'
  activeadmin (0.6.0) app/views/active_admin/resource/index.html.arb:1:in `new'
  activeadmin (0.6.0) app/views/active_admin/resource/index.html.arb:1:in `___sers__tephan__rvm_gems_ruby_______p____saftzine_gems_activeadmin_______app_views_active_admin_resource_index_html_arb___381976998_2302642480'
  actionpack (3.2.5) lib/action_view/template.rb:145:in `send'
  actionpack (3.2.5) lib/action_view/template.rb:145:in `render'
  activesupport (3.2.5) lib/active_support/notifications.rb:125:in `instrument'
  actionpack (3.2.5) lib/action_view/template.rb:143:in `render'
.
.
.

The active-admin.css.scss is:

// SASS variable overrides must be declared before loading up Active Admin's styles.
//
// To view the variables that Active Admin provides, take a look at
// `app/assets/stylesheets/active_admin/mixins/_variables.css.scss` in the
// Active Admin source.
//
// For example, to change the sidebar width:
// $sidebar-width: 242px;

// Active Admin's got SASS!
@import "active_admin/mixins";
@import "active_admin/base";

// Overriding any non-variable SASS must be done after the fact.
// For example, to change the default status-tag color:
//
//   body.active_admin {
//      .status_tag { background: #6090DB; }
//   }
//
// Notice that Active Admin CSS rules are nested within a
// 'body.active_admin' selector to prevent conflicts with
// other pages in the app. It is best to wrap your changes in a 
// namespace so they are properly recognized. You have options
// if you e.g. want different styles for different namespaces:
//
// .active_admin       applies to any Active Admin namespace
// .admin_namespace    applies to the admin namespace (eg: /admin)
// .other_namespace    applies to a custom namespace named other (eg: /other)

//= require active_admin/editor/wysiwyg

The only place I can find linear-gradient is in

Searching 482 files for "linear-gradient"

/Users/xxxxx/.rvm/gems/xxxxx/gems/activeadmin-0.6.0/app/assets/stylesheets/active_admin/mixins/_gradients.css.scss:
    4  @mixin gradient($start, $end){ 
    5    background: $start; 
    6:   background: -webkit-linear-gradient(-90deg, $start, $end);
    7:   background: -moz-linear-gradient(-90deg, $start, $end);
    8:   background: linear-gradient(-90deg, $start, $end);
    9    // IE 6 & 7
   10    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#{ie-hex-str($start)}', endColorstr='#{ie-hex-str($end)}');

3 matches in 1 file

active_admin_editor-1.0.x/app/assets/stylesheets/active_admin/editor.css.scss starts with:

@import 'active_admin/mixins';

body form .html_editor {
  .wrap {
    width: 76%;
    float: left;
  }
.
.
.

Where am I missing something. How can I get this to work?

jeudi 1 mars 2018

Partial Rendering does not work when called from another method ActionController::UnknownFormat

I have a function that does a partial render on my main page. The method works if called directly, from one of the links. The method is the following:

  def show_card
    @activity = Activity.find(params[:id])
    respond_to do |format|               
      format.js
    end
  end

I need to call this method from another method, or at least render the same thing this method renders, but with different parameters. My second method is this :

  def like_activity
    @user = current_user
    @activity = Activity.find(params[:id])
    @user.like_activity!(@activity)
    all = Activity.all
    notWanted = Activity.where(id: Activity.joins(:memberships).where({ "memberships.user_id" => current_user.id})).or(Activity.where(id: Activity.joins(:likes).where({"likes.user_id" => current_user.id}).where.not("likes.user_likes_activity" => nil)))
    queue = all - notWanted
    nextActivity = queue.first()
    redirect_to action: 'show_card', controller: 'pages', id:nextActivity.id
  end

Basically, after you like an activity, the method should call the show_card and display the new activity. However, I'm getting the following error:

ActionController::UnknownFormat

While this is the output I get on the console :

> Redirected to http://localhost:3000/pages/show_card?id=88 Completed
> 302 Found in 99ms (ActiveRecord: 59.6ms)
> 
> 
> Started GET "/pages/show_card?id=88" for 127.0.0.1 at 2018-03-01
> 17:12:35 -0800 Processing by PagesController#show_card as HTML  
> Parameters: {"id"=>"88"}   User Load (6.5ms)  SELECT  "users".* FROM
> "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 
> [["id", 2], ["LIMIT", 1]]   Activity Load (6.3ms)  SELECT 
> "activities".* FROM "activities" WHERE "activities"."id" = $1 LIMIT $2
> [["id", 88], ["LIMIT", 1]] 
> Completed 401 Unauthorized in 23ms`
> (ActiveRecord: 12.8ms)
> 
> 
>    ActionController::UnknownFormat (ActionController::UnknownFormat): 
> app/controllers/pages_controller.rb:13:in `show_card'

I'm very confused on what am I missing. I'm also using Devise, I don't know if that might have to do with the 401 - Unauthorized. If you have any idea of what could be going on it would be really appreciated if you could let me know. Thanks!

Rails 5 dropping some keys in params which contains non null values

I am moving from rails 3 to 5. I have a request to an API which accepts some parameter but is getting dropped in rails 5 for reasons I am not sure. The params which I recieved in Rails 3 was as below:

params = {"Envelope" => {"Body" => {"notifications" => {"Notification" => {"id =>" XYZ, "sObject" => {"data1" => ABC, "data2" => PQR}}}}}, "action" => XXX, "controller" => YYY, "format" => "xml", "auth" => AUTH_TOKEN, "entity" => ENTITY_NAME}

Whereas in Rails 5, the params I am receiving is:

params = <ActionController::Parameters {"entity"=>ENTITY_NAME, "auth"=>AUTH_TOKEN,  "format"=>"xml", "controller"=> YYY, "action"=> XXX} permitted: false>

How are the parameters getting dropped when the request is made?