mercredi 30 septembre 2020

options_from_collection_for_select selected value on form reload

I am a novice in RoR.

I have this line in the code along with other select objects.

<%= f.select :from_branch, options_from_collection_for_select(@branches, :id, :name, @form.from_branch), {}, :disabled => params[:repoid].blank? %>

In the webpage, when there is an error in any input, the form reloads and keeps the previously entered values intact. But for the above select tag, it resets it to the first entry. There are no blanks in the collection.

Say there are three values in the collection - A, B, C. A is the first record and selected. I select C and submit the form. Due to an error in the form it reloads. Now I want this field to have C. Instead it again goes back to A.

Any thoughts on how do I achieve this?

mardi 29 septembre 2020

jQuery doesn't output proper HTML

I have a very old Rails 3 project I'm maintaining, to which I need to add new functionality. Primarily responsiveness with Bootstrap 4.

This is what I actually want to create: http://jsfiddle.net/k1zbe4o9/. As you can see it works perfectly in the fiddle. However this project uses jQuery to dynamically change HTML. The jQuery code is fairly simple

if (best_price) {
  li_class = "list-group-item";
  li_class += " card-list-best";
}

I use this in function like so:

var list_html = $("<li class=" + li_class + ">" + list_details_html + "</li>");

However, when I do this I get this weird thing that the jQuery doesn't return this properly, so instead of having list-group-item card-list-best inside a single <li> class, somehow I get card-list-best outside that scope, and the result is as shown.

The same thing happens if I do:

if (best_price) {
  li_class = "list-group-item card-list-best";
}

Any help is appreciated.

jquery segment

lundi 28 septembre 2020

Facing issue with createing one to one mapping in ruby

I want to parse 3 arrays in ruby. For example

Array1 =[server1, server2]
array2 = [server3, server4, server5]
array3 = [server6, server7, server8]

Here in my case length of array2 and array3 will be always same. I want to use this in cookbook to execute in server where i want to make one to one mapping with array2 and array3 and search only for that particular server only. For example if i am execting this on server7 then it will return server4 and server7 only from one to one mapping and always pick first value from array1.

I am using this logic to make one to one mapping

array1 = ['a1', 'a2', 'a3']
array2 = ['b1', 'b2', 'b3']
array1.zip(array2)

But not able to parse with hostname where my cookbook is executing.

Ruby want to read file line by line and get the particular part out using gsub

I am writing a code to read a text file or csv file line by line which contain url and i want out the id of each url and print or store in text file but when i do i get an error when i use a loop before loop i am able to get it printed line by line. Can any one help me in this. Below is the my code sample.

line_num=0
File.open('/Users/divyanshu/python_imdb/channels /url.txt').each do |line|
video_links = "#{line_num += 1} #{line}"
# puts video_links

for video_link in video_links 
 
    video_lin = video_link.gsub('https://www.youtube.com/watch?v=', '')
    video_di = video_lin.gsub('?utm_source=komparify&utm_campaign=site&utm_medium=detailpage', '')
    puts video_di
end 

This the error I'm getting

Traceback (most recent call last):
        2: from /Users/divyanshu/python_imdb/url_validation.rb:6:in `<main>'
        1: from /Users/divyanshu/python_imdb/url_validation.rb:6:in `each'
/Users/divyanshu/python_imdb/url_validation.rb:10:in `block in <main>': undefined method `each' for #<String:0x00007fef3d0907c0> (NoMethodError)

jeudi 24 septembre 2020

Rails widget based design

I wanted to know if there is a Rails gem or something else that allows you to do easy widget based desgin of a homepage. Im making a budget web app as a project and the ability to move and delete information that you do not want to see is one of the things we want. I added a picture to kind of describe what we are looking for.

Thanks!

enter image description here

mercredi 23 septembre 2020

Callback inside a Module

I have something similar to this:

Module A
    Class A
        def initialize
        end

        def A
        end

        def B
        end

        def C
        end
    end
end

What I want is to run a validation before A, B, or C is executed, like a before_action, to return nil if is a condition is satisfied, for instance, if a variable is nil, return nil immediately.

I know that I can create a module:

module Callbacks
  def callbacks
    @callbacks ||= Hash.new { |hash, key| hash[key] = [] }
  end

  def before_run(method_name, callback)
    callbacks[method_name] << callback
  end

  module InstanceMethods
    def run_callbacks_for(method_name)
      self.class.callbacks[method_name].to_a.each do |callback|
        send(callback)
      end
    end
  end
end

And inside the Class A, I can call:

before_run :A, :my_validation_method
before_run :B, :my_validation_method
before_run :C, :my_validation_method

Is there any other clean way of doing this?

mardi 22 septembre 2020

Rails: How do I get reference from one .yml files to second .yml file

I have 2 models User and Account and I want to create a seed data in by using .yml file

user.rb

class User < ApplicationRecord
  has_one: account
end

and account.rb

class Account < ApplicationRecord
  belongs_to: user
end

my .yml files are

config/users.yml

user1: 
  first_name: 'John'
  last_name: 'Doe'
user2: 
  first_name: 'John'
  last_name: 'Wick'

and config/accounts.rb

account1:
  balance: 1000
account2: 
  balance: 500

so my question here is that how can i add user1 to account1 and user2 to account2 and so on. and how can i use it in seed file the create some data. Thanks :)

Do I need to install node.js to work with Ruby on rails?

I just installed Ruby and then installed rails. Created a new project. and tried to run it.

It throws an error:

C:/Ruby27/lib/ruby/gems/2.7.0/gems/webpacker-4.3.0/lib/webpacker/configuration.rb:95:in `rescue in load': Webpacker configuration file not found C:/Users/user/Desktop/projects/Ruby/blog/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - C:/Users/name/Desktop/projects/Ruby/blog/config/webpacker.yml (RuntimeError)

After some research I understood it required Yarn which belongs to node.js

Is that the only solution?

Os :Win10

Stuck with this requirement in ROR -

Create Rails API endpoints for the below requirement:

  1. Authenticated users can create an appointment as per slot availability.
  2. List of appointments for the day and week for all as well as a specific doctor.

Please help me out. :(

lundi 21 septembre 2020

Joining two tables in Rails ,which was mentioned as has_one: ".. ",class_name:"..."

class Transport::Vehicle < ApplicationRecord
    has_one :driver, class_name: "Admin", foreign_key: "driver_id"
end 
Transport::Vehicle.joins(:driver) 

produces the following SQL query

SELECT  "transport_vehicles".* FROM "transport_vehicles" INNER JOIN "admins" ON "admins"."driver_id" = "transport_vehicles"."id" AND "admins"."deleted_at" IS NULL LIMIT $1

But it should be

SELECT  "transport_vehicles".* FROM "transport_vehicles" INNER JOIN "admins" ON "admins"."id" = "transport_vehicles"."id" AND "admins"."deleted_at" IS NULL LIMIT $1

How can i get admin.id instead of admins.driver_id ??

dimanche 20 septembre 2020

Stack Level Too Deep - Error (render_parent + Redmine)

After adding render-parent to my redmine plugin I'm getting "SystemStackError (stack level too deep)" on every page. I removed the usage of render_parent to check if my code was the problem but Im still getting the error. Uncommenting the gem resolves the issue. Any Idea?

Error:

SystemStackError (stack level too deep):
lib/redmine/hook/view_listener.rb:59:in block (2 levels) in render_on' lib/redmine/hook/view_listener.rb:57:in map'
lib/redmine/hook/view_listener.rb:57:in block in render_on' lib/redmine/hook.rb:61:in block (2 levels) in call_hook'
lib/redmine/hook.rb:61:in each' lib/redmine/hook.rb:61:in block in call_hook'
lib/redmine/hook.rb:58:in tap' lib/redmine/hook.rb:58:in call_hook'
lib/redmine/hook.rb:96:in call_hook' app/views/welcome/index.html.erb:26:in _a474c089af486ba567547e1ef0d07fff'
lib/redmine/sudo_mode.rb:63:in `sudo_mode'

Environment:

  • Redmine version 3.4.13.stable
  • Ruby version 2.5.5-p157 (2019-03-15) [x86_64-linux]
  • Rails version 4.2.11.1

mercredi 16 septembre 2020

How to delete the unwanted word that is being generated at the end of the Url in Rails

i have an url of: party_detail_search/search but the url of [party_detail_search/search?breadcrumbs] and [party_detail_search/search?adycfaf] also redirected to party_detail_search/search with the same web contents...i don't want the duplicate pages, how do i solve this problem

Rails adding a row to a csv that only has headers and no data removes the headers

I am reading a CSV file from a CDN and adding data to it then writing it back to a CDN for this reason I can't use append file.

I am also reordering the file which is why I have to turn it back into a CSV::Table

This code is a slimed down version of what I have but the problem is still replicated.

class SomeForm::Form
  class << self

    def add
      data = CSV.parse(open(csv_file_url).read, headers: true)
      data << ['david', 'smith'] # this will be dynamic
      # data = data.sort_by { |row| [row['Firstname'], row['Lastname']] }
      write_csv_file(CSV::Table.new(data).to_csv)
    end


    def csv_file_url
      #somecode to get the file_url
    end

    def write_csv_file(data)
      #somecode to write the file to the cdn
    end
  end
end

CSV file

Firstname,Lastname

So if I run SomeForm::Form.add with the csv file as above it outputs (removing the headers)

,
David,smith

However if the CSV file has at least one record in eg

Firstname,Lastname
Steve,Cougan

and run the code it adds the new record as expected

Firstname,Lastname
Steve,Cougan
david,smith

I would like to get this to work with csv with data in and csv with just the headers in.

As a aside this is for a rails3 project, though the above is replicatable in rails 5 as well

Thanks in advance

upload file within a specific folder in a bucket

im using gem 'aws-sdk-s3' & im successfully able to upload my file on AWS bucket but I don't know how can I upload my files in a specific folder in my bucket ?

mardi 15 septembre 2020

Using ActiveStorage with Aws in Rails Api

I'm learning rails and I have a task to make an API in rails that can take image params from the front-end and save it to the backend in the image model with its caption.

  1. I have credentials from Aws secret id & key as well.

  2. yes, I know how to install Active Storage , gem "aws-sdk-s3", gem "active storage validation.

  3. I know to configure storage.yml & production.rb.

  4. I'll add a line has_one_attached :image in my Restaurant Model.

But i don't know what kind of params I'll get from the front-end developer & how can I test that params or URL in my postman from my side . & how to return that image in json format to the frontend developer after saving it.

i want to upload restaurant images from users.

database.yml with postgres schema

I'm cloning a remote postgresql database to my local dev in order to run some tests, in the remote db the data I need is actually in a schema within the db, I haven't figured out how to remove schema name from the dump, so I guess I'll be working with local data in a schema within the db.

I couldn't find any documentation about how to configure database.yml to specify the database and schema to be used for the connection.

Here's my database.yml so far, (not working)

development:
  adapter: postgresql
  database: <%=ENV['DATABASE_NAME']%>
  schema: schema_name
  host: <%=ENV['DATABASE_HOST']%>
  username: <%=ENV['DATABASE_USER_NAME']%>
  password: <%=ENV['DATABASE_PASSWORD']%>
  pool: <%=ENV['RAILS_MAX_THREADS'] || 5 %>
  timeout: 5000

any ideas?

Getting TypeError - no implicit conversion of Symbol into Integer when trying to save

I am upgrading an RoR API app from Rails 3 to Rails 6. In one of the forms, I am getting TypeError - no implicit conversion of Symbol into Integer error when saving.

This is my params defined:

def narrative_params
  name_params = (params[:narrative] || {})[:name].keys
  description_params = (params[:narrative] || {})[:description].keys
  params.require(:narrative).permit(:support_url, :guest_access_allowed, 
                   disable_navigation, :disable_new_window, :enable_social_sharing, :customer_id, :user_id, 
                  :support_url, narrative_image_ids: [:_id], sub_groups_id: [:_id], template_id: [:_id], 
                  name: name_params, description: description_params)
end

The data is getting saved to the database but the save method is returning this error. I have spent a lot of time on this, I don't understand what I am missing here. Please help.

dimanche 13 septembre 2020

Como fazer uma multipart post request com a biblioteca RestClient?

Galera,

como fazer um (multipart) post request com ruby para salvar imagens em um arquivo? Como meu conhecimento em rb ainda é muito pequeno, mesmo lendo a documentação da biblioteca eu ainda não consigo. Alguém pode ajudar? Talvez postando um exemplo de código que já tenha feito pra isso? Estou estudando mais ainda precisaria de um passo a passo. Detalhe, (mesmo se pudesse ainda não saberia, mas) não posso usar rails.

vendredi 11 septembre 2020

how to view exception backtrace in exception_handler gem?

we are using rails 6 with 'exception_handler', '~> 0.8.0.0'.

we able to configure this gem and able to show error message but we like to get an error backtrace but we not see an option to get backtrace details for and exception.

can someone help me to understand this gem support to provide backtrace?

if you know any other gem which supports backtrace with a custom error page with rails 6 then let us know.

Capybara / RSpec Ensure somethinng does not exist anywhere on the page

I want to find out how to ensure something does not exist on the page, specifically, a div with a known value. Essentially, I'm removing an element and I want to test that the element with 3 classes does not exist anywhere on the page, also there are multiple elements with the same classes, so the important part is making sure the inner of the div tag does not exist.

For example:

<div class="blah blah2 blah3">my pizza</div>

There may be 20+ divs with the same classes blah blah2 and blah3, however, I need to ensure that NONE of them include the term "my pizza", how can I do this with an expect()?

I tried something like this but it didn't work:

expect(all(:css, 'div.blah blah2 blah3').value).not_to eq('value'))

Any ideas? Tips?

UPDATE: I tried adding assert_no_text('my pizza') but this checks the whole page and I don't know if this will change in a future release of the software.

mercredi 9 septembre 2020

uninitialize constant user (work with dto)

I'm learning rails using Devise for authentication purpose and make a User by Rails generate Devise user it creates a user model for me & every thing is works fine But when i put my file to User component
Component

where I have user_dto & user_service file as well.

problem occur when I try to create a migration by rails g migration add_authentication_token_to_users "authentication_token:string{30}:uniq" and i got an error here **uninitialized constant User (NameError) ** error is resolved when i put back user.rb file to models but i have to work in this way , is their any solution to generate a migration with putting this user.rb file to component not in model.

5 Star-Rating in Rails API

I'm learning rails and my work is from the backend side and I'm going to make a restaurant rating system in which a user can rate a restaurant he checkin before. I'm getting user_id & rating e.g (4,5,3) from front-end now I don't know how to get the overall restaurant rating. I have an idea below

s = sum of rating on a particular restaurant 
t = total no of rating on that reataurant 

Restaurant overall rating = s/t 

Here im getting these values from my Rating model where I store resturant_ID , User_id , user_rating, Overall_rating .

i don't know here im going on the right path or not but I need guidness from seniors.

mardi 8 septembre 2020

Return specific values from array of hashes - JSON

Hi am learning rails and in my app, I'm getting values in json format from
res = @client.spots(params[:location][:lat], params[:location][:lng], :types => ['restaurant','food'], :radius => 500)

in my res object, I'm getting these values

{
  "json_result_object": {
    "business_status": "OPERATIONAL",
    "geometry": {
      "location": {
        "lat": 31.4734563,
        "lng": 74.2794873
      },
      
    },
    "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
    "name": "CP Five Star",
    "opening_hours": {
      "open_now": true
    }
      }
    ],
    "place_id": "ChIJjfE-TdoDGTkRMom8KQfI9Uc",
    "plus_code": {
      "compound_code": "F7FH+9Q Lahore, Pakistan",
      "global_code": "8J3PF7FH+9Q"
    },
   
  },
  "reference": "ChIJjfE-TdoDGTkRMom8KQfI9Uc",
  "place_id": "ChIJjfE-TdoDGTkRMom8KQfI9Uc",
  "vicinity": "Bilal Arcade, Abdul Haque Road, Block G Block G Phase 1 Johar Town, Lahore",
  "lat": 31.4734563,
  "lng": 74.2794873,
  "viewport": {
    "northeast": {
      "lat": 31.4748154802915,
      "lng": 74.28081473029151
    },
    "southwest": {
      "lat": 31.4721175197085,
      "lng": 74.2781167697085
    }
  },
  "name": "CP Five Star",
  "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
  "types": [
    "restaurant",
    "food",
    "point_of_interest",
    "establishment
  
}

now I just want to return a JSON array containing just the values below place_id , name , lat lng , icon

& Sorry I'm using image just to show my actual response in terminal image

lundi 7 septembre 2020

Ruby - How to Merge a Hash into a method

I have this method

def method1
 {
  headers: { 'Content-Type' => 'application/json' }
 }
end

and this another method for merge a another key and value into this method1 hash, so

def merge_hash
  method1.merge!(body: { params: 123 }
end

so when i call method1 again i expect he returns a marged body and my questions is why not this happens or how i can do it?

mercredi 2 septembre 2020

Rails, Pagination offset not working, after clicking on '2' number(pagination) or other's page's

I am trying to pass offset in pagination.

  params[:page] = 1 if params[:page].nil?
  @pagination_count = (params[:pagination_count].present?) ? params[:pagination_count] : 50
  offset = ''
  if params[:page] != 1 
    offset = "limit 50 offset #{(params[:page].to_i - 1) * 50}"
  else
    offset = "limit 50"
  end
 posts_count =  ActiveRecord::Base.connection.execute(query + ' where ' + query2 + query1).count 
 @posts =  ActiveRecord::Base.connection.execute(query + ' where ' + query2 + query1 + offset).to_a.paginate(page: params[:page], per_page: 50, total_entries: posts_count) 

But, it's not working on click 2 page(pagination number), 2nd page is viewed but, data didn't get. on 1st page data displayed.

Rails, Pagination offset not working, after clicking on '2' number(pagination) or other's page's

I am trying to pass offset in pagination.

  params[:page] = 1 if params[:page].nil?
  @pagination_count = (params[:pagination_count].present?) ? params[:pagination_count] : 50
  offset = ''
  if params[:page] != 1 
    offset = "limit 50 offset #{(params[:page].to_i - 1) * 50}"
  else
    offset = "limit 50"
  end
 posts_count =  ActiveRecord::Base.connection.execute(query + ' where ' + query2 + query1).count 
 @posts =  ActiveRecord::Base.connection.execute(query + ' where ' + query2 + query1 + offset).to_a.paginate(page: params[:page], per_page: 50, total_entries: posts_count) 

But, it's not working on click 2 page(pagination number), 2nd page is viewed but, data didn't get. on 1st page data displayed.

Find User from the params we get

im a not a rails expert but i want to know that how can I find the User by its email as I'm getting before in params . & in else section I want to create new user by using that parameters

  def google
    user = User.find_by email: user[:email]
    if user
      user.generate_new_authetication_token
      json_response "User Information & already exist" , true, {user: user}, :ok
    else
          ??????????
    end
    if user.save
      json_response "Signed up Successfully ", true, {user: user}, :ok
    else
      json_response "something wrong ", false, {}, :unprocessable_entity
    end
  end

And another private function from which I'm getting user params

private

  def google_params
    params.require(:user).permit(:uid , :email )
  end

mardi 1 septembre 2020

Rails, NoMethodError - undefined method `paginate' for #

    posts =  ActiveRecord::Base.connection.execute(query + ' where ' + query1)
    @posts = posts.paginate(page: params[:page], per_page: 50)

Tried to do pagination, but giving error undefined method `paginate'

pagination used in view.

    <div class="col-xs-12 col-sm-12 col-md-12"><%= will_paginate @posts, class: 'pull-right marg', renderer: BootstrapPagination::Rails %></div>