mercredi 29 janvier 2020

How to prevent changing values or intercepting requests from BURP suite

I am working on posting a form data in ruby on rails. But the post request can be intercepted with burp suite and values in the form can be altered. So there is anyway to prevent it.

How to create composite form input using formtastic

I'm trying to create a form that looks in a specific way using formtastic but I have no idea how to go about it. I'm on an old version of formtastic (2.2.1) but help with any version is also appreciated. The form works properly, it's just out of order from what i'm trying to achieve.

I have tried;

= form.input :enable_input_field, :as => :boolean, label: ''
= form.input :column_name, :label => "Input Label"

Which gives the checkbox above the Input Label. Like below; Result Presently gotten with above code

The result I would like to get is seen in the picture below; Image showing what desired result should look like

mardi 28 janvier 2020

Cannot run rails server and rake db:migrate

Whenever I try running my rails server or any commands the following error keep appearing:

could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

Does anyone know how to fix this error? Its been bothering me that I can not run any of my projects. Thank you!

samedi 25 janvier 2020

How to include a mixin/module in ALL ActiveAdmin controllers?

I have written a module - JsonLog - that uses the append_info_to_payload hook provided by Rails to add some custom metrics to the logging instrumentation. I want to include/mixin this module in all the controllers of ActiveAdmin.

I've tried the following, and it works...

ActiveAdmin.register MyModel do
  controller do
    include JsonLog
  end
end

...but this will force to me write the boilerplate code in every single model/controller that I'm registered with ActiveAdmin. How do I do this in one place (and in the process also ensure that this boilerplate is never missed out)?

vendredi 24 janvier 2020

How can I convert OpenSSH public key into OpenSSL in Ruby (or Rails)

I have public keys in a database and need them to validate JWT tokens. The keys are in OpenSSH public key format, so I need to convert them into PEM format like this:

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAx9jNrkPwjH12qVhmpKs/MLfvsYy5uob+jx68Mdsv5tmZG5HVq6nm
sYKkcDdwLseShWREIOmB0lC/bhaaihuAvs4ZZcDRKnrq2FX+WQz9/mHScr1kQTgB
adRdQWzG3KXeOJJiKSBfNHVn3Iixdba/IX5rYhARbDMqPQfwz08gKHbFLuNogNN0
hm5yTFQU1z0bhR87dHFJgfwQSVloeNKTsXleoGZqGBNbjMdF0HOEvQaWzenQHJde
dTaF39Ok6q0k4QsSHyuzmoXy30O3oe31D7mu4QQOk/Lj61zVZrR25YvGYpn0ym+d
cWxKFyeVX/McstRhu7wD1iu0kj74A2VhrwIDAQAB
-----END RSA PUBLIC KEY-----

Is there a way to convert a OpenSSH public key into a OpenSSL one with Ruby (not with openssl)?

I already found this: https://gist.github.com/tombh/f66de84fd3a63e670ad9 But unfortunately it's throwing an error in recent Ruby versions.

I also found the SSHKey gem but that doesn't seem to offer that functionality.

/usr/bin/env: ruby_executable_hooks: No such file or directory

I'm trying to create a systemctl service that would start a ruby on rails application on server reboot

the following command in a run.sh file

#!/bin/sh
service httpd stop
rails s -p 80 -d 

works on the command line. However when systemctl attempts it I get the subject error. What is the cause of such error and what can I do to stop it?

Nested_form with scoped selects of the same has_many through relation

I am working on a product admin section. I have productvariants, which can have many productattributevalues through productvariantdetails.

productattributevalues (green, yellow, S, XL) belongs_to productattributes where I have specified attributes such as: color, size and material.

I would like to have a nested form on my productvariants/_form where I can choose (optionally) if a productvariant has an productattributevalue of: size or color applied.

I changed my models and introduced two aliases for productattributevalues. One for each attribute.

class Productvariant < ActiveRecord::Base
  has_many :productattributevalues
  has_many :productvariantdetails
  has_many :productattributevalues, :through => :productvariantdetails
  has_many :productattributecolors, :through => :productvariantdetails, :source => :productattributevalue
  has_many :productattributesizes, :through => :productvariantdetails, :source => :productattributevalue
  accepts_nested_attributes_for :productvariantdetails, :allow_destroy => true
end

class Productattributevalue < ActiveRecord::Base
  attr_accessible :value, :productattribute_id
  scope :product_color, joins(:productattribute).where('productattributes.attributename' => 'color')
  scope :product_size, joins(:productattribute).where('productattributes.attributename' => 'size')
  belongs_to :productattribute
end

This is my view

<%= form_for [:admin, @productvariant], :html => {'role' => 'form' } do |f| %>
    .
    .
    .
  <%= f.fields_for : productattributecolors do |ff| %>
      <%= ff.label "Productattribute: Color" %>
      <%= ff.select(:productattributecolor, Productattributevalue.product_color.uniq.order('id asc').map{|s| [s.value, s.id]}, {:selected => params[:productattributecolor], :include_blank => false, :prompt => "Select color"}, {}) %>
  <% end %>
  <%= f.fields_for : productattributesizes do |ff| %>
      <%= ff.label "Productattribute: Size" %>
      <%= ff.select(:productattributesize, Productattributevalue.product_size.uniq.order('id asc').map{|s| [s.value, s.id]}, {:selected => params[:productattributesize], :include_blank => false, :prompt => "Select size"}, {}) %>
  <% end %>
    .
    .
    .
    <%= f.submit "Save" %>
<% end %>

How can I get this working?

Thank you in advance!

jeudi 23 janvier 2020

Rails: Unique validation with nested attributes

Table 1 - Product

has_many :widget_groups
accepts_nested_attributes_for :produts_widget_groups

validates_uniqueness_of :name, on: :create,
                                     if: proc { |product| product.has_category? }

Table 2 - ProductsWidgetGroup

belongs_to :product
belongs_to :widget_group
has_many :products_widget_group_deatils

Table 3 - ProductsWidgetGroupDetail

belongs_to :products_widget_group
belongs_to :product
accepts_nested_attributes_for :product

I have a form, which I am using to save the product in (table 1) and the sending the nested attributes for table 2 and table 3.

Here I am trying to put the unique name validation for product which we are saving through the table 3 but I have some issue with that.

I need to get the model validation error message for the product object of table 1 then only I can show them the error in the frond end. But here the validation error message going to the product object of table 3. Is there anyway we can achieve that?

Rails: how to redirect in controller action with nested attributes form

I am trying to to redirect after a nested form has been submitted.

I have two resources: products and productvariants, where a product has_many productvariants. On my ProductsController.rb I have an add_sku action:

class Admin::ProductsController < ApplicationController

def add_sku
  @product = Product.find(params[:id])
  @product.productvariants.build
  @page_title = 'Create new productvariant'
end

And a relative form of:

<%= form_for [:admin, @product], :html => {'role' => 'form' } do |f| %>
  <%= f.fields_for :productvariants, Productvariant.new do |ff| %>
    <div">
      <%= ff.label :hero_id %>
      <%= ff.select(:hero_id, Image.joins(:albums => :section).where(:sections => {:title => 'shop'}).order('file_name asc').map{|s| [s.file_name, s.id]}, {}, {}) %>
    </div>
    <div>
      <%= ff.label "Variant title" %>
      <%= ff.text_field :title %>
    </div>
    <div>
      <%= ff.label :price %>
      <%= ff.text_field :price %>
    </div>
    <div>
      <%= ff.label :stock %>
      <%= ff.text_field :stock %>
    </div>
  <% end %>
  <div class="actions create">
    <%= f.submit "Save" %>
  </div>
<% end %>

I would like to find out how I would redirect to the show page of productvariants after I hit submit. Something similar to this:

class Admin::ProductsController < ApplicationController

def add_sku
  @product = Product.find(params[:id])
  @product.productvariants.build
  @page_title = 'Create new productvariant'
  ? if @product.productvariants.save
  ?   flash[:notice] = "The productvariant has been successfully added to the product."
  ?   redirect_to :controller => :productvariants, :action => :show, :id => @productvariant
  ? else
  ?   render :action => :add_sku
  ? end
end

How could I implement this?

Thank you in advance!

mercredi 22 janvier 2020

Rails: How to create a has_many through association with an alias/cass_name

I am trying to transform my HABTM to has_many through relations. Sometimes I have to connect the same models in different ways. For example to specify different roles for authors.

With a HABTM I would do this through the declaration of a class_name option. Just like:

class Project < ActiveRecord::Base
  has_and_belongs_to_many :curators, :class_name => :author, :through => :projects_curators
end

class ProjectsCurator < ActiveRecord::Base  
  attr_accessible :project_id, :author_id
  belongs_to :project
  belongs_to :author
end

class Author < ActiveRecord::Base
 has_and_belongs_to_many :projects, :through => :projects_curators
end

But when I transform everything into a has_many through:

class Project < ActiveRecord::Base
  has_many :project_curators
  has_many :curators, :class_name => :author, :through => :project_curators
end

class ProjectCurator < ActiveRecord::Base  
  attr_accessible :project_id, :author_id
  belongs_to :project
  belongs_to :author
end

class Author < ActiveRecord::Base
  has_many :project_curators
  has_many :projects, :through => :project_curators
end

I get: Could not find the source association(s) :curator or :curators in model ProjectCurator. Try 'has_many :curators, :through => :project_curators, :source => <name>'. Is it one of :author or :project?

When I add :source

has_many :curators, :class_name => :author, :through => :project_curators, :source => :author

I get:

uninitialized constant Project::author

How can I get this working? Thank you very much in advance!

Rails: find all resources not already connected through join table

I am trying to rewrite actions which connect and disconnect products to and from projects. Currently my select_to_project view shows all products, but I would like it to display only products which have not been already connected to a given project.

Products and projects are connected through a join table

class Product < ActiveRecord::Base
  has_and_belongs_to_many :projects, :join_table => "projects_products"  
end

class Project < ActiveRecord::Base
  has_and_belongs_to_many :products, :join_table => "projects_products" 
end

class ProjectsProduct < ActiveRecord::Base
  attr_accessible :project_id, :product_id

  belongs_to :project
  belongs_to :product
end

In my products controller I currently have:

def select_to_project
  @project = Project.find(params[:id])
  @products = Product.find(:all)
end

def select_from_project
  @project = Project.find(params[:id])
end

Obviously the select_to_project view currently displays all possible products, even those which are already connected through the join table.

I thought the select_to_project action should be changed to something like this:

def select_to_project
  @project = Project.find(params[:id])
  @products = Product.joins(:projects => :products).where('products_projects_join.product_id IS NOT ?', @product)
end

But I currently get an MySQL error when I try to load the relative view:

Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1)' at line 1: SELECT `products`.* FROM `products` INNER JOIN `projects_products` ON `projects_products`.`product_id` = `products`.`id` INNER JOIN `projects` ON `projects`.`id` = `projects_products`.`project_id` INNER JOIN `projects_products` `products_projects_join` ON `products_projects_join`.`project_id` = `projects`.`id` INNER JOIN `products` `products_projects` ON `products_projects`.`id` = `products_projects_join`.`product_id` WHERE (products_projects_join.project_id IS NOT 1)

How can I get this query working in Rails 3?

Thank you very much in advance.

mardi 21 janvier 2020

Ruby - Rails - RVM or Rbenv only one version of Ruby can work

I have two projects, one using ruby-2.7.0, the other using ruby-2.6.5.

I've just realized there is a weird issue with my Ruby/Rails setup on the latest OS X. Either using RVM or Rbenv, every time I installed over two versions of ruby, only one version ends up working (2.7.0). The bundle as well as gem commands on the other will no longer work but give a Traceback....(RuntimeError).

In the past 6 hours, I have reinstalled rbenv, uninstalled rbenv, installed rvm. I've also tried uninstalling all non-system Ruby versions and Rails as well. Nothing seems to help.

Below is the error shown in my console:

(base) ➜  ~ rvm list
=* ruby-2.6.5 [ x86_64 ]
   ruby-2.7.0 [ x86_64 ]

# => - current
# =* - current && default
#  * - default

(base) ➜  ~ bundle -v
Traceback (most recent call last):
ruby: invalid option -:  (-h will show valid options) (RuntimeError)
(base) ➜  ~ gem -v
Traceback (most recent call last):
ruby: invalid option -:  (-h will show valid options) (RuntimeError)
(base) ➜  ~ rvm use 2.7.0
Using /Users/nahua/.rvm/gems/ruby-2.7.0
(base) ➜  ~ bundle -v
Bundler version 2.1.4
(base) ➜  ~ rvm use 2.6.5
Using /Users/nahua/.rvm/gems/ruby-2.6.5
Traceback (most recent call last):
ruby: invalid option -:  (-h will show valid options) (RuntimeError)

Please let me know what information I should provide in order to help you understand the problem better. Cheers!

vendredi 17 janvier 2020

How to acess has_many_through file urls of file uploaded using carrierwave in rails

How can I access the url of the file which is present in the related model and uploaded by using carrier wave. I have three Models like:

class ThreeDModel < ApplicationRecord
  has_many :three_d_model_animations
  has_many :animations, through: :three_d_model_animations
end

2nd

class Animation < ApplicationRecord
  has_many :three_d_model_animations
  has_many :three_d_models, through: :three_d_model_animations
  mount_uploader :video, AnimationVideoUploader
  validates_presence_of :video
end

3rd

class ThreeDModelAnimation < ApplicationRecord
  belongs_to :animation
  belongs_to :three_d_model
  validates_presence_of :animation_file
  mount_uploader :animation_file, ThreeDModelAnimationUploader
end

so, now I want to access the url of the video which is present in the Animation model uploaded using carrier wave,along with the fields in the ThreeDModelAnimation and url of the aimation file.
Because if go with the joins and select query the url to the files will be lost. please tell me how to acheive it without loosing the file_url to the file. Thanks in advance

jeudi 16 janvier 2020

What is LightweightAttributes in rails?

Can anyone explain me LightweightAttributes in rails? And what is use of lightweight attribute in active record model?

Rails CSV remove column that have empty header

I am receiving a csv file that has some blank headers but data exists in these columns. I want to remove the blank header and it's associated column in rails.

Sample csv

#report
,Code,Price,Orders,,Mark,
1,X91,4.55,4,xxx,F,23

What I'd like returned:

Code,Price,Orders,Mark
A91,4.55,4,F

This is what I have so far as there is also comments on the csv which i am ignoring.

CSV.open("output.csv", "w") do |output_csv|
          CSV.foreach("out.csv", encoding: "bom|utf-8", skip_lines: /^#/, headers: true).with_index(0) do |row, i|
            output_csv << row.headers if i == 0
            output_csv << row
          end
        end

lundi 13 janvier 2020

how can i render form from other controller using link_to in rails?

Hi have project scaffold and that had project list. i have created stage scaffold with some field. now i want to render stage form in show page of project view. i tried but i am getting error. i want to use a link_to in show page of the project show to the form of the stage.

routes.rb

Rails.application.routes.draw do
  resources :stages
  resources :projects
end

projects show.html.erb

<p id="notice"><%= notice %></p>

<p>
  <strong>Project name:</strong>
  <%= @project.project_name %>
</p>
<%= link_to 'Edit', edit_project_path(@project) %> |
<%= link_to 'Back', project_managers_path %>

<br>
<br>
<%= link_to "Add Stage", stage_form_path %>

project_controller.rb

  def index
    @projects = current_user.projects.all.paginate(page: params[:page], per_page: 15)
  end


  def show
    @stages = Stage.new
  end

each project has many stages relation in model.

dimanche 12 janvier 2020

How to use i% to create & assign symbols in one line?

The following code is resulting in an error:

    %i[@date @doctor @patient] = date, doctor, patient

However, this works:

    @date, @doctor, @patient = date, doctor, patient

How do I use %i to create the symbols and assign them values on the same line?

How works these methods in controllers, assets in js?

I have this example
And i wanna understand what it is " ||= " in this method? How it works?

First segment

 def current_user
            @current_user ||= User.find(session[:user_id]) if session[:user_id]
          end

also, i dont know what does (function()) mean in Ruby on rails. Its not simple function(), why is it inside brackets?

Second example

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();

}).call(this);

vendredi 10 janvier 2020

not able to access localhost:3000 outside vmware

i am running webrick default ROR server inside vmware in ubuntu. i have host window as Window 10.but in window 10 browser i am not able to access the 0.0.0.0:3000 . i have ruby on rails code, how can i host in my own machine server? in window10 browser i get error like- error

puma.rb


threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
threads threads_count, threads_count


port        ENV.fetch("PORT") { 3000 }


environment ENV.fetch("RAILS_ENV") { "development" }

# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }


plugin :tmp_restart

Naming a new entity for white-label platform

Before starting, I noticed that this is not a tech-specific question (just a naming debate), so let me know if this post is not appropriate.

I'm building a car rental platform for a company and we have plans to turn this product into some sort of white label that other car rental companies (and any company that has a car fleet) could use.

Since I want to start with the right foot, I know that the first step is to build a new "Entity" that "reflects" these organizations.

Here are some simplified Ruby examples of my project.

class User < ApplicationRecord
  has_many :payments
  has_many :bookings
end

class Car < ApplicationRecord
  validates :price_per_day, numericality: { greater_than_or_equal_to: 0 }
  has_many :bookings
end

So, by adding a new "Organization"

class User < ApplicationRecord
  has_many :payments
  has_many :bookings
  belongs_to :organization
end

I can make my Fleet Admins to have access only to specific users, cars, etc. I can also make my users browse only cars from the organization, and even add proper UI and styling based on the organization. However, the name organization looks pretty ambiguous. Unfortunately most of the platform offers company and corporate plans as one of the biggest business models so I can't use that name since from now on "Many companies (in a corporate plan) belongs to one specific organization". I've even thought in some sort of Workspace concept (Slack inspired), but not really sure if it's the most proper word.

Once again, I'm sorry if naming debates are not allowed in here, just a non-english speaker that is really keen into good naming in code.

mardi 7 janvier 2020

Ruby code adding single \ to escape #, instead of adding double slash to the '#'

ruby adding single \ to escape # instead of double slash

for example, the '#' in string 'sd@#' is preceded with single '\' like this 'sd@#' automatically. I think it should add '\\'(double slash) to escape '#'. Is it a bug in ruby syntax? if not is there a way to escape it manually

Please help

Capybara::ExpectationNotMet: Timed out waiting for Selenium session reset

I'm having an issue with Capybara (2.18.0) and Webdrivers (4.1.2) on Rails 3.22.2.5.

My tests are meeting their expectations but it seems Selenium hangs when trying to close or reset causing the test to fail. Weirdly I had this test working just fine before, and now with no changes, I'm getting this.

2018-01-12 00:00:00 WARN Selenium [DEPRECATION] Selenium::WebDriver::Error::UnhandledAlertError is deprecated. Use Selenium::WebDriver::Error::UnexpectedAlertOpenError (ensure the driver supports W3C WebDriver specification) instead.
        lists only periods that are semesters (FAILED - 1)
************************************************************************
Factory Bot Payload
{:pay_seniority=>{:create=>1}, :assignment_note=>{:create=>1}, :user=>{:create=>1}, :period=>{:create=>2}}
************************************************************************

Failures:

  1) looking at your shifts new unavailability specific time create by semester lists only periods that are semesters
     Failure/Error: example.run

     Capybara::ExpectationNotMet:
       Timed out waiting for Selenium session reset
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/capybara-2.18.0/lib/capybara/selenium/driver.rb:145:in `reset!'
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/capybara-2.18.0/lib/capybara/session.rb:127:in `reset!'
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/capybara-2.18.0/lib/capybara.rb:314:in `block in reset_sessions!'
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/capybara-2.18.0/lib/capybara.rb:314:in `reverse_each'
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/capybara-2.18.0/lib/capybara.rb:314:in `reset_sessions!'
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/capybara-2.18.0/lib/capybara/rspec.rb:22:in `block (2 levels) in <top (required)>'
     # ./spec/features/your_shifts_spec.rb:6:in `block (3 levels) in <top (required)>'
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/timecop-0.9.1/lib/timecop/timecop.rb:201:in `travel'
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/timecop-0.9.1/lib/timecop/timecop.rb:129:in `send_travel'
     # /home/jforgue/.rvm/gems/ruby-2.3.8/gems/timecop-0.9.1/lib/timecop/timecop.rb:51:in `freeze'
     # ./spec/features/your_shifts_spec.rb:5:in `block (2 levels) in <top (required)>'
     # ./spec/spec_helper.rb:104:in `block (2 levels) in <top (required)>'

I'm pretty confident the deprecation warning is because Capybara is out of date but because this is Rails 3.22.2.5 Capybara and Webdrivers can't be updated to a higher version.

This is my test:

it 'lists only periods that are semesters' do
  create :period, :semester, name: 'fall'
  create :period, name: 'not fall'
  visit current_path
  click_link 'New Unavailability'
  click_link 'Specific time'
  click_link 'Create by Semester'
  expect(page).to have_select 'unavailability_period_id', options: ['fall']
end

And here is how I'm setting my driver in my spec_helper:

Capybara.javascript_driver = :selenium_chrome_headless

What is MigrationProxy in rails?

  1. Brief explanation of ActiveRecord MigrationProxy in rails migration?
  2. When it will be used in rails application?
  3. What is the use of Migration Proxy?

How can make a decision based on multiple models in Rails?

i have three model project_site, project_manager and human_resource. each model has status Boolean attribute i want to print "approve" only if all status==true but want to print "reject" if any one of the status is set to false. each status has nil value by default.

        <% if project_site.human_resources.empty? %>
              <td class="pending fi-eye"><%= " Pending" %></td>
            <% elsif %>
              <% project_site.human_resources.each do |human_resource| %>
                <% if human_resource.status == false %>
                  <td class="rejected fi-x"><%= ' Rejected' %></td>
                <% elsif human_resource.status == true %>
                  <td class="approved fi-check"><%= " Approved" %></td>
                <% end %>
              <% end %>

              <% elsif %>
                <% project_site.project_directors.each do |project_director| %>
                  <% if project_director.status == false %>
                    <td class="rejected fi-x"><%= ' Rejected' %></td>
                  <% end %>
                <% end %>

                <% elsif %>
                  <% project_site.project_managers.each do |project_manager| %>
                    <% if project_manager.status == false %>
                      <td class="rejected fi-x"><%= ' Rejected' %></td>
                    <% end %>
                  <% end %>
            <% end %>

How to select data from multiple model in rails

i have three model project_manager, project_director, and human_resource each has a status Boolean field how can i print some thing in rails if Boolean value of these three model is true. currently i am accessing data from model by doing this-

            <% if project_site.project_managers.empty? %>
              <td class="pending fi-eye"><%= " Pending" %></td>
            <% else %>
              <% project_site.project_managers.each do |project_manager| %>
                <% if project_manager.status == false %>
                  <td class="rejected fi-x"><%= ' Rejected' %></td>
                <% elsif project_manager.status == true %>
                  <td class="approved fi-check"><%= " Approved" %></td>
                <% end %>
              <% end %>
            <% end %>

            <% if project_site.project_directors.empty? %>
              <td class="pending fi-eye"><%= " Pending" %></td>
            <% else %>
              <% project_site.project_directors.each do |project_director| %>
                <% if project_director.status == false %>
                  <td class="rejected fi-x"><%= ' Rejected' %></td>
                <% elsif project_director.status == true %>
                  <td class="approved fi-check"><%= " Approved" %></td>
                <% end %>
              <% end %>
            <% end %>

            <% if project_site.human_resources.empty? %>
              <td class="pending fi-eye"><%= " Pending" %></td>
            <% else %>
              <% project_site.human_resources.each do |human_resource| %>
                <% if human_resource.status == false %>
                  <td class="rejected fi-x"><%= ' Rejected' %></td>
                <% elsif human_resource.status == true %>
                  <td class="approved fi-check"><%= " Approved" %></td>
                <% end %>
              <% end %>
            <% end %>

i want to print approved if all these three model status value is true how can i do that in rails?

lundi 6 janvier 2020

Preciso criar uma exceção caso o relatório venha em branco ou com dados zerados [closed]

Tentei criar um raise mas como sou novato em ruby on rails to perdido sobre o que fazer uma exceção caso o relatório venha vazio. Segue abaixo o código do service:

class ReportService def self.generate_report(params, type, data_type = 'data') "#{type}Report".constantize.send("report_#{data_type}", params) end

def Not_Blank raise Exception.new('Deu ruim!') unless @data_type.blank? end end

O controller ficou assim:

class Backend::ReportUsersController < Backend::Controller respond_to :html, :xlsx, :pdf load_and_authorize_resource :user, :parent => false before_action :check_permissions

def report if params[:user_report][:institutes].reject!(&:blank?).blank? return redirect_to( report_users_path, alert: I18n.t('report.user.error.institute_required') ) end

if params[:user_report][:start_at].blank?
  params[:user_report][:start_at] = I18n.l(User.first.created_at.to_date, format: :default)
end

if params[:user_report][:end_at].blank?
  params[:user_report][:end_at] = I18n.l(Date.current, format: :default)
end

params[:user_report][:current_user] = current_user.name
if params [:user_report][:total_participants].blank?
  return redirect_to(
    report_users_path,
    alert: I18n.t('report.user.error.cannot_generate_blank_or_empty_report')
  )
end
@report = ReportService.generate_report(params[:user_report], 'User')
@pagy, @report_data = pagy_array(JSON[@report[:data]], size: [2,2,2,2])

end

def generate_file if params[:format] == 'pdf' institutes = Institute.where(id: params[:report][:institute_ids])

  if institutes.size == 1
    @logo = institutes[0].logo
  end

  respond_to do |format|
    format.pdf do
      render pdf: I18n.t('activerecord.models.user.other'),
      margin: { top: 30 },
      footer: {
        font_size: 10,
        left: "#{I18n.t('report.research.general_labels.generated_at')}: " +
          "#{I18n.l(DateTime.current, format: :default_without_seconds)} | " +
          "#{I18n.t('report.research.general_labels.by')}: " +
          "#{@current_user.name}",
        right: "[page] #{I18n.t('report.research.general_labels.of')} [topage]"
      },
      orientation: 'Landscape',
      template: "backend/report_users/layout_pdf.html.erb"
    end
  end
elsif params[:format] == 'xlsx'
  report = ReportService.generate_report(params, 'User', 'excel')

  respond_to do |format|
    format.xlsx { render xlsx: report[:file], filename: I18n.t('report.user.file_name.report_users') }
  end
end

end

private

def check_permissions raise CanCan::AccessDenied unless @current_user.full_manager? end end

dimanche 5 janvier 2020

i not able set form data into database in rails

hey i have project_site model where user uploads name file into database. and another model i have is project_manager which has accept and reject Boolean field and remark field along with each project_site entries. but i am unable to set remark and status boolean data into project_manager database. here is my code- project_manager.rb

class ProjectManager < ApplicationRecord
  belongs_to :project_site
end

project_site.rb

class ProjectSite < ApplicationRecord
  has_many :project_managers, dependent: :destroy
  validates :name,:attendance, presence: true
end

project_manager_dashboard

  <table>
    <thead>
      <tr>
        <th>Uploaded By</th>
        <th>Attendance File</th>
        <th colspan="2"></th>
      </tr>
    </thead>

    <tbody>
      <% @project_sites.each do |project_site| %>
        <tr>
            <td><%= project_site.name.titleize %></td>
            <% if project_site.attendance? %>
              <td><%= link_to "View Attendance", project_site.attendance.url, :class => "fi-page-export-csv" %></td>
            <% else %>
              <td>No File Present</td>
            <% end %>

            <td>
              <%= form_for [ @project_site, @project_manager ] do |f| %>
                <div class="row">
                  <div class="medium-6 columns">
                    <%= f.radio_button :status, true  %>
                    <%= f.label :approve %>
                    <%= f.radio_button :status, false  %>
                    <%= f.label :reject %>
                  </div>
                  <br>
                  <br>
                  <div class="medium-6 cloumns">
                    <%= f.label :remark %><br/>
                    <%= f.text_area :remark %>
                  </div>

                    </div>
                  <div>
                    <%= f.submit 'Submit', :class => 'button primary' %>
                  </div>

              <% end %>
            </td>
            <td><%= link_to 'Action', project_site, :class=>'button tiny primary' %></td>
        </tr>
      <% end %>
    </tbody>
  </table>

project_manager_controller.rb

class ProjectManagersController < ApplicationController

  def index
   @project_sites = ProjectSite.all.order("created_at DESC").paginate(page: params[:page], per_page: 10)
   @project_manager = ProjectManager.new
   #@project_manager.project_site_id = @project_site.id
  end


  def create
     @project_manager = ProjectManager.new(remark_params)
    @project_manager.project_site_id = params[:project_site_id]
    @project_manager.save

    redirect_to project_managers_path
  end

  def remark_params
    params.require(:project_manager).permit(:remark, :status)
  end
end

routes.rb

  resources :project_sites
  resources :project_managers

how can i set appove reject field for admin in rails

i have post model and admin model i am able to render post model index to the admin model view but i want admin should have approve and disapprove button. i have added Boolean status to admin model and established has one relation to post model. now i have no idea how can i set status to each post. what logic should i write in admin controller and routes? guys could you help? i am using rails 5 admin controller

def index
@post=Post.all
end

i want status approve and reject button on the same dashboard along with post entries

samedi 4 janvier 2020

Which technicque would NOT be useful to share common attributes and behaviors between two ActiveRecord Models?

  1. a Rails Concern
  2. a polymorphic association
  3. single table inheritance
  4. a Ruby module as a mixin

all of above can be used to share common attributes and behaviors between more than 2 ActiveRecord models. I searched several articles but couldn't figure it out clearly.

vendredi 3 janvier 2020

How can we add same_site attribute on rails 4 application?

I have rails 4 application and I see now crome is expected to not supporting cookies without same_site attribute.

My application is iframe-based and I have tried to add

response.headers['Set-Cookie'] = 'Secure;SameSite=None'

in ApplicationController < ActionController::Base class on before action filter but it not working sill my session object not set to same_site attribute

can someone help me how we can set the same_site attribute without upgrade my rails version.

jeudi 2 janvier 2020

not able to render form from different model in rails

i am new to rails was building new rails app. i have post model and a post_status model that contains Boolean status attribute.the database connection between post and post_status model is belongs_to and has_many. i want to render all posts from post model along with accept reject radio submit button that sets Boolean of post_status model. i tried but i am getting error please help.

routes.rb

  resources :posts do
    resources : post_status
  end
get '/admin' => 'admin#index'

admin index.html.erb

  <table>
    <thead>
      <tr>
        <th>title</th>
        <th>User Email </th>
        <th>Uploaded Date</th>
        <th>Status</th>
        <th colspan="2"></th>
      </tr>
    </thead>

    <tbody>
      <% @posts.each do |post| %>
        <tr>
            <td><%= post.title %></td>
            <td><%= post.user.email %></td>
            <td><%= post.created_at.strftime('%d-%m-%Y') %></td>

            <% if post.post_status.empty? %>
              <td><%= " Pending" %></td>
            <% else %>
              <% post.post_status.each do |post_status| %>
                <% if post_status.false == false %>
                  <td><%= ' Rejected' %></td>
                <% else  %>
                  <td ><%= " Approved" %></td>
                <% end %>
              <% end %>
            <% end %>
            <td><%= "HERE I WANT TO RENDER THE FORM WITH ACCEPT REJECT AND SUBMIT BUTTON FOR EACH POST TO ADMIN DASHBOARD" %></td>
        </tr>
      <% end %>
    </tbody>
  </table>

mercredi 1 janvier 2020

Is there is a way to detect previous changes in serialized hash attribute in ruby

I am trying to detect changes in a hash attribute in my model. But I am not able to detect changes because it is serialized. I am trying to detect changes after_commit callback.

Here is the code //

settings.rb

serialize :additional_settings, Hash after_commit :publish_to_central

def publish_to_central if self.previous_changes.present? account.model_changes = self.previous_changes.to_hash end end

after updating the additional_settings hash, the value gets updated but self.previous_changes returns empty.

I am not able to detect changes only for serialized hash and array attributes, remaining works fine. Can anyone help with this.

active job not saving data in the database rails

i want to save this message five time from active jobs not from controller. is there anyway to that ? here message.save just returning true and its not saving the message in databas.


class MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(message)
    for i in 0..5
      message.save!
      ActionCable.server.broadcast 'chat', {message: render_message(message)}
    end
  end

  private

  def render_message(message)
    MessagesController.render(
        partial: 'message',
        locals: {
            message: message
        }

    )
  end
end

this code is from model.

class Message < ApplicationRecord
  belongs_to :user
  after_create_commit {
    MessageBroadcastJob.perform_later(self)
  }
end

how to create realtion between two model and render to other controller view in rails

i have i project_site model that contains name email and project details. i have generated another model project_remark model that contains boolean attribute value. i have a controller name manager_dashboard_controller.rb. i can i link my boolean attribute value to each project_site and print them in list with accept and reject submit button with project_site on the manager dashboard. what changes i need to do in my code . i have already created association between project_site(has_many :project_remarks) and project_remark(belongs_to :project_site) model.

  resources :project_sites do
    resources :project_remarks
  end