jeudi 30 août 2018

Pass let parameter to shared context

I have a shared context and want to pass some variable outside to this shared example. I currently make it like this:

shared_context "test" do |param1, param2|
    before :each do
      puts "context:"
      puts param1
      puts param2
    end
  end

  describe 'test' do
    let(:name1) { "name_1" }
    include_context "test", name_1, "name_2"
    ...
  end

But I got error:

An error occurred while loading ./spec/car_spec.rb.
Failure/Error: include_context "test", name_1, "name_2"

NameError:
  undefined local variable or method `name_1' for RSpec::ExampleGroups::Car::Test:Class
  Did you mean?  name
                 name

It can't recognize the variable defined in let, how should I pass a variable defined outside of a shared context into it? Thanks!

Adding parameter before saving in Rails 3.2 controller

Rails 3.2

I have an API workspace in my Rails 3.2 application.

I can make calls to create tickets, and within the calls, I'm passing a list of parameters. The model has a ticket_type param, that is not passed through the API call, so I want to add that parameter, prior to saving.

Within the ticekts_controller.rb, in the create call, I added the following:

@ticket.ticket_type = 'urgent'

followed by:

@ticket.save

I am not getting any error messages, but the ticket_type in the tickets table remains NULL.

I cannot do this through the model, because this is behavior that I want to restrict only to the API controller. I've already checked the ticket.rb model, and it ticket_type is in the attr_accesible list.

Any ideas?

Setting database connection pool size for delayed_job?

I'm trying to understand database connection pools in Rails, and starting to get somewhere :)

I understand the default pool size is 5. In Unicorn you can set the pool size as a config, which will be the pool of connections per Unicorn worker process. So if you have 2 dynos each running 3 processes, and you're using the default pool of 5, you could have up to 2*3*5=30 database connections open.

I'm also using background workers, but not sure how I'd set the pool size there. I checked, and even if I set the pool as 2 for Unicorn, the worker process still has the default pool of 5. Is there a simple way to set the pool size for background workers using delayed_job?

mercredi 29 août 2018

How to access raw SQL statement generated by update_all (ActiveRecord method)

I'm just wondering if there's a way to access the raw SQL that's executed for an update_all ActiveRecord request. As an example, take the simple example below:

Something.update_all( ["to_update = ?"], ["id = ?" my_id] )

In the rails console I can see the raw SQL statement so I'm guessing it's available for me to access in some way?

PS - I'm specifically interested in update_all and can't change it to anything else.

Thanks!

wkhtmltopdf falis for 1000+ pages ruby on rails

Generating a pdf of 1000+ pages fails in case of header supplied. layouts/header is a header.pdf.haml file. After going through various suggestions, increased the open files limit on ubuntu also didn't work.

respond_to do |format|
  format.html
  format.xlsx
  format.pdf { render pdf: "Test report", dispoistion: :attachment,
      :show_as_html => (params[:d].present? && params[:d] == "true"),
      layout: "pdf.html.haml",
      margin: {
        top: 38
      },
      header: {
        spacing: 2,
        html: {
          template: 'layouts/header',
          formats:  [:pdf],
          handlers: [:haml],
          layout: nil,
          locals: {
            title: "Test Report"
          }
        }
    }
  }
end

mardi 28 août 2018

Any ruby gem available for managing users availability and appointments

I am looking for gem which can manage user availability like booked for a particular time or free during that time period.

I am using https://fullcalendar.io/ for managing map view of availability and recurrence gem for making scheduled appointments. I am looking for a gem which could manage users free time and booked time

enter image description here

Guidance to setup the local server for existing ROR app on Windows

I am new to ROR and I am trying to run the existing rails app on local server. But somehow it fails when i am trying to migrate the db . rake aborted! LoadError: cannot load such file -- eventmachine C:/promotracks-rails/config/application.rb:7:in <top (required)>' C:/promotracks-rails/Rakefile:4:in'

( I have ruby,rails,gem,bundler installed)

Select value from another unassociated table

I have two tables, say T_A and T_B, and they have their own models. Two tables have correlations but don't have something like has_many belongs_to and they're not allowed to have those explicit correlations, so we can't use joins.

The relation between them, say from field_A1 of T_A, we have a field_B1 of T_B to map it, and we want to have field_A1 and field_B2 of two tables.

If we are using raw sql query, it will simply be:

select T_A.field_A1, T_B.field_B2 where T_A.field_A1=T_B.field_B1

But, how to do this without using raw SQL query? Thanks!

lundi 27 août 2018

Rails app config.eager_load set to nil?

During cap <env> deploy I get the following error, but all my environment files are set accordingly. What is the deal?

config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly:

  • development - set it to false
  • test - set it to false (unless you use a tool that preloads your test environment)
  • production - set it to true

UPDATE: I believe this is because capistrano is not pulling down the latest changes from the branch. Does capistrano cache the branch somewhere? I believe this is the case because the latest release which was 10 minutes ago doesn't include my most recent changes.

jeudi 23 août 2018

How can i use complex direct query instead of activerecord in a rails application?

I have one rails application, which has one function that read values from database using active-record like this way

def get_all_products
 products = Product.for_locations(location_id)
 products.includes(:a, { b: [:c]}, {d: [:e]}, :f).each do |product|  
   product_forms = product.product_forms.sort_by{ |a| a[:sequence_no] } 
   .......
   .......
 end
end

this above function will take some time to process so this running as a background job. Now i would like to move this portion to a separate rails API application, so that will process and put that data in database, but this new application doesn't have any models and all, so how can i use this same function get_all_products in new rails API application, there i can't use active-record to get the data because there is no model, and even if i use direct query, its bit complicated, is there any way to achieve this?

To create roles and permission dynamically in ruby on rails

I am working on a Ruby on rails project.

There are 5 Tables such as user table; role table; permission table; user_permission table; and role_user table.

Using a Current User ID,

Here Super Admin should able to create roles and permissions dynamically, i tried using cancan gem but getting error and not working properly,Is there any other solution for this, or can we create it without using any gems?

Kindly tell me any suggestion as i am a beginner

These are the model

User model

has_many :role_users has_many :roles, through: :role_users

validates :email,:presence => true

RoleUser model

belongs_to :user

belongs_to :role

Role model

has_many :role_permissions has_many :role_users has_many :users, through: :role_users has_many :permissions, through: :role_permissions

validates :name, presence: true

RolePermission model

belongs_to :permission belongs_to :role


Permission Model

has_many :permission_actions has_many :role_permissions has_many :roles, through: :role_permissions validates :subject_class, presence: true validates :action, presence: true

Syntax error in spatial query?

I wrote a function for found all pois around a track

controller :

def index
  @track = Track.friendly.find(params[:track_id])
  @tracks = Track.where(way_id: @track.id)
  @way = Way.find(1)
  @poi_start = Poi.find(@way.point_start)
  @pois = @track.pois.sleepsAndtowns
  @pois = @way.poi_around_track_from(@poi_start, 50000, @pois)
end

way.rb

def poi_around_track_from(poi, dist, pois)
  around_sql = <<-SQL
  SELECT
  ST_DWithin(
    ST_LineSubstring(
    way.path,
    ST_LineLocatePoint(way.path, pta.lonlat::geometry) + #{dist} / ST_Length(way.path::geography),
    ST_LineLocatePoint(way.path, pta.lonlat::geometry) + 100000 / ST_Length(way.path::geography)
  ),
  ptb.lonlat,
  2000) is true as pois
  FROM ways way, pois pta, pois ptb
  WHERE way.id = #{self.id}
    and pta.id = #{poi.id}
    and ptb.id = #{pois.ids}
  SQL
  Poi.find_by_sql(around_sql).pois
end

This function return : syntax error at or near "[" LINE 13: and ptb.id = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

What's wrong, how can I fix it ?

Ruyb on Rails DB entry in a model (RoR 3)

There is:

  • Project (has_many :group_permissions)
  • GroupPermission (belongs_to :project)

I have a form where you can create a new project. A project has several attributes like name, status etc. and now important: iit. iit is selectable with radio buttons: yes or no.

What I want:

If someone selects yes on iit in the Project form, there should be a new record in GroupPermission. So in EVERY project where iit= 1 there should be a certain GroupPermisson.

Can I make / check this in the GroupPermission model? Like if

class GroupPermission < ActiveRecord::Base
    if Project.where(iit: 1)
     make me a record for each project

end

Can I even make database entries in the model like so?

Is this the right way?

Thank you in advance.

dimanche 19 août 2018

How can i match a dynamically changing url in VCR

In my Ruby on Rails application there are 2 Localhost servers running. I am writing test cases for the 1st server and so I have to mock the 2nd server. For this I am using VCR to record the responses I get from the 2nd server and play the recorded cassette while running the tests on the 1st server.

I am stuck at the part where the 1st server makes a request to 2nd server(the session_id in the URL changes each time) and I want the response to be same every time it makes a request.

vendredi 17 août 2018

Need to store the post_id and user_id in read_statuses table using rails

When i initiate the show action the controller want to store the post_id and user_id into the another table.But it need to store for the first occurrence only For eg. (if user 1 opens the post 1 for the first time it creates an entry into the database but not at when he view the same post for the second time) Post controller show cation will be:

def show

@post = @topic.posts.find(params[:id])
@rate=@post.ratings.all
@rate = Rating.where(post_id: @post.id).group("rate").count
@read_status= ReadStatus.create(user_id: current_user,post_id: @post.id)

end

Post model:

class Post < ApplicationRecord
belongs_to :user
has_many :read_statuses
has_many :users,through: :read_statuses
end

User model:

class User < ApplicationRecord
has_many :posts
has_many :read_statuses
has_many :posts, through: :read_statuses
end

Read status model:

class ReadStatus < ApplicationRecord
belongs_to :user
belongs_to :post
end

jeudi 16 août 2018

Ruby sorting two arrays of array to align the common element in both arrays

I reached at the following step while working on some log processing task

process_start_array = [["process_1", "Start", "2018-06-15", "13:00:50,560"], ["process_2", "Start", "2018-06-15", "13:00:50,762"], ["process_3", "Start", "2018-06-15", "13:00:50,827"], ["process_4", "Start", "2018-06-15", "13:00:50,154"]]

and

process_end_array = [["process_4", "End", "2018-06-15", "13:00:50,560"], ["process_1", "End", "2018-06-15", "13:00:50,762"], ["process_2", "End", "2018-06-15", "13:00:50,827"], ["process_3", "End", "2018-06-15", "13:00:51,484"]]

As you can see that some process take long and ends later while some process do not take long and finish faster.

In order to calculate the process execution time and perform ruby date time subtraction, I would like to sort the process_end_array based on the process_start_array so that that start and end events of the same process are aligned. How can I achieve that?

Rails 4 scope expands incorrectly

In an app that was recently ported from Rails 3 to Rails 4, I have a model called MeetingSeries with the following relation:

has_many :meetings, :foreign_key => :series_id

The Meetings model has the following scope:

scope :future, -> { where("start_time is not NULL and end_time > ?", DateTime.now())}

So if I have a particular meeting series:

@m = MeetingSeries.find(42)

I can grab all the meetings from that series like this:

@m.meetings

In this case, I correctly get a small number of meetings that are in just the specified series. However, when I use the scope:

@m.meetings.future

I suddenly get all future meetings, not just the ones in the specified series. The SQL queries that get built for these two are very different and make obvious the fact that the series ID is not part of the query:

 irb(main):003:0> @m.meetings.count()
(1.5ms)  SELECT COUNT(*) FROM `meetings` WHERE `meetings`.`type` IN ('Meeting') AND `meetings`.`series_id` = 9856
=> 78

Versus:

 irb(main):004:0> @m.meetings.future.count()
(16.7ms)  SELECT COUNT(*) FROM `meetings` WHERE `meetings`.`type` IN ('Org::Happenings::ScheduledHappening', 'Org::Happenings::RoomBooking', 'Org::Happenings::Meeting', 'Org::Happenings::Unavailability', 'Meeting', 'Unavailability') AND (start_time is not NULL and end_time > '2018-08-16 15:35:09.609774')
=> 3422

This behaved properly under Rails 3, so I gather the erroneous behavior stems from some difference in either the way scopes work, or ActiveRecordRelations work, in Rails 4. Any ideas?

RoR 3.2.6: Uncaught ReferenceError: jQuery is not defined

currently I'm working on an older ruby on rails project.

In use:

  • ruby 2.2.10
  • rails 3.2.6
  • jquery-rails 3.1.5
  • bootstrap-sass 2.3.2.2
  • execjs 2.7.0
  • therubyracer 0.12.3

My console prints Uncaught ReferenceError: $ is not defined. Then I tried to define $ = jQuery which printed Uncaught ReferenceError: jQuery is not defined which means that jQuery is not properly included. I also read a lot of other posts about this issue but nothing has fixed mine so far.

application.js (snippet)

    //= require jquery
    //= require jquery_ujs
    //= require bootstrap

application.html.erb (snippet)

    <head>
      <title>Creative Title</title>
      <%= stylesheet_link_tag    "application", :media => "all" %>
      <%= javascript_include_tag "application" %>
      <%= csrf_meta_tags %>
    </head>

There's nothing special in the dev console ... - it's driving me really crazy.
I really appreciate your help.

mardi 14 août 2018

i want to recive value from 'bootstrap Custom forms' in Ruby

<%= form_for :content, url: contents_path, method: :post do |f| %>

  <%= f.label :inout %> <!-- 수입 지출 목록 -->
  <%= f.text_field :inout %><br>

  <div class="input-group mb-3">
    <div class="input-group-prepend">
      <label class="input-group-text" for="inputGroupSelect01">Options</label>
    </div>
    <select class="custom-select" id="inputGroupSelect01">
    <option selected>Choose...</option>
    <option value="1">결혼식</option>
    <option value="2">장례식</option>
    <option value="3">돌잔치</option>
    </select>
  </div>

  <% if option == 1? %>
    <%= f.hidden_field :category, value=>"결혼식" %>
  <% end %>

  <%= f.label :title %>
  <%= f.text_field :title %>

  <%= f.label :cost %>
  <%= f.text_field :cost %>

  <%= f.label :memo %>
  <%= f.text_area :memo %>

  <%= f.submit %>
<% end %>

if i select option value one, i store "결혼식" in category

and i want to see "결혼식" in show view

but now my program occur error enter image description here

how can i do?

assets.gzip V.S. Rack::Deflater

I am trying to implement compression on my app. How is it different to implement middleware config.middleware.use Rack::Deflater or config.middleware.insert_before ActionDispatch::Static, Rack::Deflater in config/application.rb compared to enabling config.assets.gzip = true in my config/environments/.rb ?

reference:

https://robots.thoughtbot.com/content-compression-with-rack-deflater#rails-3-and-4 https://guides.rubyonrails.org/asset_pipeline.html#serving-gzipped-version-of-assets

Update globalize3 to globalize

I have an old Rails 3 application; I updated it to rails 4. But when I update the globalize3 to globalize gem I lost translates attributes:

class Role < ActiveRecord::Base
  include MaskedPermissions

  # Relations
  has_many :users, inverse_of: :role, dependent: :restrict
  has_many :folder_permissions, class_name: 'RoleCmsPermission', inverse_of: :role, dependent: :destroy

  # Attributes
  translates :name

  attr_accessible :codename, :client_role, :translations_attributes

  accepts_nested_attributes_for :translations

  # Validations

  # Delegations

  # Callbacks

  # Scopes

  # Class methods
  def self.codenames
    pluck(:codename)
  end

  # Define a codename method for each role present
  Role.codenames.each do |codename|
    define_singleton_method(codename) do
      where(codename: codename).first
    end
  end if ActiveRecord::Base.connection.table_exists? 'roles' # Otherwise rake tasks fail before roles table is created
end

Then when I use this class I get:

[12] pry(Role):1> cd all.sample
  Role Load (0.9ms)  SELECT `roles`.* FROM `roles`
[13] pry(#<Role>):2> self
=> #<Role id: 19, codename: "auditor", client_role: true, created_at: "2013-05-13 11:15:30", updated_at: "2013-05-13 11:15:30", global: false, permissions_mask: 1>
[14] pry(#<Role>):2> name
NoMethodError: undefined method `zero?' for nil:NilClass
from /Users/toni/.rvm/gems/ruby-2.1.6@afs-update/gems/activerecord-4.0.9/lib/active_record/associations/alias_tracker.rb:30:in `aliased_name_for'

The old app has a initilializer like this, I need to remove this, but it seems to do the same as inside globalize:

    module Globalize
  module ActiveRecord
    module ActMacro
      def translates(*attr_names)

        options = attr_names.extract_options!
        attr_names = attr_names.map(&:to_sym)

        unless translates?
          options[:table_name] ||= "#{table_name.singularize}_translations"
          options[:foreign_key] ||= class_name.foreign_key

          class_attribute :translated_attribute_names, :translation_options, :fallbacks_for_empty_translations
          self.translated_attribute_names = []
          self.translation_options        = options
          self.fallbacks_for_empty_translations = options[:fallbacks_for_empty_translations]

          include InstanceMethods
          extend  ClassMethods, Migration

          translation_class.table_name = options[:table_name] if translation_class.table_name.blank?

          has_many :translations, :class_name  => translation_class.name,
                                  :foreign_key => options[:foreign_key],
                                  :dependent   => :destroy,
                                  :extend      => HasManyExtensions

          if options[:required]
            validates :translations, associated: true
          end

          after_create :save_translations!
          after_update :save_translations!

          if options[:versioning]
            ::ActiveRecord::Base.extend(Globalize::Versioning::PaperTrail)

            translation_class.has_paper_trail
            delegate :version, :versions, :to => :translation
          end

          translation_class.instance_eval %{
            attr_accessible :#{(attr_names | [:locale]).join(', :')}
          }

          # detect and apply serialization
          attr_names.each do |attr_name|
            serializer = self.serialized_attributes[attr_name.to_s]

            if serializer.present?
              if defined?(::ActiveRecord::Coders::YAMLColumn) &&
                 serializer.is_a?(::ActiveRecord::Coders::YAMLColumn)

                serializer = serializer.object_class
              end

              translation_class.send :serialize, attr_name, serializer
            end
          end
        end

        new_attr_names = attr_names - translated_attribute_names
        new_attr_names.each { |attr_name| translated_attr_accessor(attr_name) }
        self.translated_attribute_names += new_attr_names
        if options[:required] && new_attr_names.present?
          translation_class.class_eval do
            validates *new_attr_names, presence: true
          end
        end
      end

    end

  end
end

I really do not know what to do.

Update link_to tag

I am a complete newbie to Ruby and Rails and has an work assigned where I am calling a function and getting the output of link_to in return. Now I want to add aria attributes to the returned html. The code is in ruby and need to be updated in *.rb file only.

lundi 13 août 2018

Ruby on Rails 5.2 Ajax con formularios remotos

estoy estancado en esta parte ya que, siguiendo las indicaciones del video, no me funciona como debería. al agregar el comentario, tengo que recargar para que este aparezca y, una vez que éste aparece, sigue mostrándose el email.

coffeescript: 
$(document).on "ajax:success", "form#comments-form", (ev, data)-> 
  console.log data 
  $(this).find("textarea").val("") 
  $("#comments-box").append("<li> #{data.body} - #{} </li>") 
$(document).on "ajax:error", "form#comments-form", (ev,data)-> 
  console.log data 



<%= 
  form_for([@article,@comment], remote: true, html: { id: "comments-form" , 
:"data-type" => "json" }) do |f| %>

show:

 <ul id="comments-box">
  <% @article.comments.each do |comment| %>
  <li>
   <%= comment.body %> - <%= comment.user.email %>
  </li>
  <%end%>
 </ul>

Writing an ActiveRecord/AREL query to select the coin held by the greatest numbers of users

Just to explain: I have a users model, and users have many portfolios. Each portfolio has many positions, and each position belongs to a coin. I want to select the coin that is held by the greatest number of users, but am struggling a bit to come up with the correct query. I could imagine writing something like 'find the coin that has the most positions, where the user_ids of the positions are distinct'. Is that the right idea, and how does type that up?

From where I learn new ruby concepts

I am new in ROR. I want to learn ROR basic to advance level so i need some beast sites where i go ahead and learn ROR easily. Please help me if you know some free sites. Thanks in advance.

dimanche 12 août 2018

Rails : Unpermitted parameter: :track_ids with complex form

My schema database

I would like to create a Town who have several neested attributes :

My controller :

def new
  @town = Town.new(params[:user_id])
  @user = current_user.id if current_user
  @poi = @town.build_poi(user_id: @user)
  @track = @town.poi.tracks.build
end

def create
  @town = Town.new(town_params)
  @town.user_id = current_user.id if current_user
  if @town.save(town_params)
    if params[:images]
      params[:images].each do |image|
        @town.town_images.create(image: image)
      end
    end
  redirect_to root_path, notice: t(".town_created")
  else
    render :new
  end
end

And my strong params :

def town_params
  params.require(:sleep).permit(
    :name,
    :user_id,
    { :service_ids => [] },
    { :poi_attributes => [:id,  :city, :pk, :latitude, :longitude,  :poitable_id, :poitable_type, :user_id, :track_ids =>[] ] },
    { :image_attributes => [:image, :town_id]})
end

I get the following error : Unpermitted parameter: :track_ids

I try to use permit! but I always have the same error. What's wrong ?

samedi 11 août 2018

In Which technology should i make my ECommerce app Rails or MEAN stack? and Why?

I am confused between on Ruby On rails and JavaScript in which both the technology is great but for better development on future use which one should i used?

vendredi 10 août 2018

Rails Admin gem Logout

Iam using rails_admin gem to manage data on top of that i'm using devise gem for authentication. Everything works fine however i'm not able to see any logout out button for user to get off the page. I just see the edit button. Below is the screen shot please take a look. Not able to see any logout option. Could anyone please help me out to get logout button. Many thanks

enter image description here.

jeudi 9 août 2018

Rails: Find records before/after a specific position

Current call:

@current_organization.users.order(gaming_drops: :desc)

Returns ActiveRelation:

[
  Record_1,
  Record_2,
  Record_3,
  Record_4,
  Record_5
  ...,
  Record_200
]

I don't need all records, I just need 1 record before Record_30 (id=current_user.id), and 4 records after.

Expected result:

[
  Record_29,
  Record_30, <--- current_user.id
  Record_31,
  Record_32,
  Record_33,
  Record_34
]

Can't install ruby to /usr/local on Ubuntu 14.04 using rbenv

Have to re-install ruby on our server because our Rails installation is failing (some OpenSSL error). I successfully uninstalled it by running $sudo rm -rf $(rbenv prefix 1.9.3-p194) Because the command rbenv uninstall failed. Then I couldn't $rbenv rehash because:

rbenv: cannot rehash: /usr/local/rbenv/shims/.rbenv-shim exists

But I'm not sure if that matters.

Anyways now when I try to run $rbenv install -v 1.9.3-p194 I get a permission denied error:

cannot create directory '/usr/local/rbenv/versions/1.9.3-p194': Permission denied

But when I run $sudo rbenv install -v 1.9.3-p194 the ruby is installed successfully in /home/anbranin/.rbenv/versions/1.9.3-p194, which is NOT where it's supposed to be, right? It's supposed to be in /usr/local.

Total newbie here trying to run a legacy rails application--our devops person is out--so I'm lacking in knowledge about Linux servers.

My only idea at this point is to just sudo mv the files to usr/local but will that work?

Add preload to a styleseet included in asset-pipeline

I have a page on my website (made on ruby on Rails), for which I want to increase the performance. I am using "Audits" of Google Chrome to test the "Preformance".

One of the things that I am getting in "Opportunities" section are: "Pre-load key requests". What it is telling me is, to use use preload for some of the CSS which are taking time. What I am unable to understand here is that, the CSS that it is telling me to preload is in application.scss file. How do I preload a css which is getting precompiled? Is that even possible?

What I know is that if I am using a stylesheet say, temp.css on a page, I can use 'link rel="preload" href="temp.scss" as="style"' and it will preload the file. Now, how do I do this for an asset which is getting precompiled. I am really confused. Kindly help if my understanding is wrong. Thanks!

mercredi 8 août 2018

How to precompile a pdf asset in Rails?

In Rails 3.2.11 app I'm trying to publish my app to Heroku.

In the assets folder I have a pdf subfolder with some pdf files inside.

In my production.rb file I have added the following:

config.assets.precompile += %w[*.png *.jpg *.jpeg *.gif *.pdf]
config.assets.precompile += ["*.js"]
config.assets.precompile += ["*.css"]
config.assets.precompile += ['pdf/*']
config.assets.precompile += %w( ricerca_wg.pdf  )

If I check the pdf assets paths on my console I get:

 Rails.application.config.assets.paths
=> ["/Users/Augusto/Sites/wisegrowth/app/assets/images",
 "/Users/Augusto/Sites/wisegrowth/app/assets/javascripts",
 "/Users/Augusto/Sites/wisegrowth/app/assets/pdf",
 "/Users/Augusto/Sites/wisegrowth/app/assets/stylesheets",
 "/Users/Augusto/Sites/wisegrowth/vendor/assets/javascripts",
 "/Users/Augusto/Sites/wisegrowth/vendor/assets/stylesheets",
 "/Users/Augusto/.rvm/gems/ruby-1.9.3-p551/gems/jquery-rails-2.3.0/vendor/assets/javascripts",
 "/Users/Augusto/.rvm/gems/ruby-1.9.3-p551/gems/coffee-rails-3.2.2/lib/assets/javascripts",
 "/Users/Augusto/.rvm/gems/ruby-1.9.3-p551/gems/formtastic-2.1.1/app/assets/stylesheets"]

But when I run

rake assets:precompile RAILS_ENV=production

everything is precompiled BUT the pdf files and in my production app on Heroku I get the following error:

ActionView::Template::Error (ricerca_wg.pdf isn't precompiled):

how to solved the 301 error wix project?

Nara Coding Labs: We provide engaging website and application development and also design them with your marketing goals in mind. We also do give full CRM Services to our clients. https://naracodinglabs.com/web-development/

mardi 7 août 2018

Allow unconfirmed users to access certain pages which require authentication

I use the Rails Stack with

  • devise
  • warden
  • confirmable

Now I have a certain requirement related to email confirmation and access provision to unverified users. Let's say there are 3 categories of pages:

  1. case 1 - requires no authentication.
  2. case 2 - requires authentication and also require the user to be confirmed.
  3. case 3 - requires authentication (correct username and password combination) but user need not be confirmed to access them.

With devise and confirmable, implementing case 1 and case 2 is a breeze. Once the user does login/signup, I redirect to "confirm your email page".

My problem is with case 3. Suppose the user does his login/signup. He is yet to confirm his email address but should be allowed to visit certain case 3 routes. When he visits a case 3 routes, I expect:

  • no redirection
  • valid session

Devise with confirmable either allows all the pages to be visited by confirmed users or none. It does not allow access to certain pages with authentication but without confirmation.

I tried overriding the devise confirmed? by implementing this logic:

class ApplicationController < ActionController::Base
   before_filter :verify_user
   def verify_user
       $flag = true if CERTAIN_ROUTES.include?(action_class)
   end
end

class User < ActiveRecord::Base
   def confirmed?
      $flag || !!confirmed_at
   end
end

This barely works for sign in but not for sign up. Also, this is an extremely bad way to achieve it. How should I approach this problem? Other functionalities work fine.

How do you run and debug Ruby on Rails from Visual Studio Code?

  • How can you launch Ruby on Rails using the built-in Visual Studio Code Launch/Debug features?

  • How do you fix the Debugger terminal error: Process failed: spawn rdebug-ide ENOENT error?

How to upload and download a file in ruby on rails?

I am fairly new to rails. I have a controller 'Links controller' where I have defined: def gen file.open() .... where I open and edit a file. I want the user to upload a file and the edited file gets automatically downloaded. How do I go about creating the view?

lundi 6 août 2018

error while trying to send bulk emails using ruby

I'm trying to send some emails using ruby script and i get error after sending to about a few emails then gives the error as shown below. Note: i'm using office365 as smtp provider. this is the initial folder containing the scripts below folder containing the scripts

this is the email handler script below email handler 1

email handler 2

then this is the main sender script main 1

continue main 2

main 3

so when i try to send the mail, first it sends one mail multiple times then the rest email fails as shown below cmd main

then this happens error msg

Now my question is why the emails are failing after sending a very few mails successfully. i think there is an error somewhere in the script. Any help?

mercredi 1 août 2018

Assign class to link_to using html slim

I'm working on a html slim file for a Ruby on Rails project. I want to create a button of class btn btn-primary (I'm using bootstrap) for a controller action. Name of controller is default_responses and action is edit. So I first did:

= link_to 'Test this', :controller => 'default_responses', :action => 'edit', :id => params[:id].to_i

This would become

<a href="/default_responses/7/edit">Test this</a>

where 7 is the id parameter and is correct for my case. However, it is not a button at all, just an anchored tag. It also redirects me to the correct page.

Then I tried

 = link_to 'Test this', :controller => 'default_responses', :action => 'edit', :id => params[:id].to_i, class: 'btn btn-primary'

which gave me

<a href="/default_responses/7/edit?class=btn+btn-primary">Test this</a>

This is still not what I want as it is not a button still.

Also tried = link_to 'Test this', :controller => 'default_responses', :action => 'edit', :id => params[:id].to_i, :class=> 'btn btn-primary'

It returned <a href="/default_responses/7/edit?class=btn+btn-primary">Test this</a> which is still wrong.

Any suggestions? Thanks.

Ruby Rails Excel Format Array Manipulation

I need some help/idea on how to dynamically position values in a 2D array.

Basically, I have a condition that must be met and that determines which column should the value be written.

This is what I have (a loop that pass conditions before writing the value):

@records.each do |client|

  client_info  = Report.get_client_info(client)
  client_address = Report.get_client_address(client)

  client_records = []

  client_records << [client_info.id, client_info.full_name]

  if @include_address == "1"
    client_address.each_with_index do |address, i|
      if client_records[i].present?                                    
        client_records[i][2] = address.full_address               
        client_records[i][3] = address.address_type   
      else
        client_records << ["","", address.full_address, address.address_type]
      end             
    end
  end

  if @include_contact == "1"
    client_contact.each_with_index do |contact, i|
      if client_records[i].present?                                    
        client_records[i][4] = contact.value                         
        client_records[i][5] = contact.label
      else
        client_records << ["","","","", contact.value, contact.label]               
      end
    end
  end
end

Problem is: IF I want to make another condition, and the condition in between the two (conditions) is not true, the position of the column value set by: client_records[i][2] >> 2,3 etc... is hard coded, instead of the third condition occupying the place of the second condition's columns, it naturally leaves it blank and stays at the same place.

This is how it would look like:

enter image description here

Instead of:

enter image description here

How can I work around this?