dimanche 31 mai 2020

Rails and JQuery-Load DB data into Textfields for save and delete

I have below data in database.My requirement-I have two options in dropdwon Get and Set. If i select Set option from dropdown , textfields along with checkbox needs to be created inside table dynamically with values of database ParaName,Datatype,Values as below.User can edit and delete records by selecting checkbox.I am new to ruby on rails.Can someone help,how to implement this?

UI Design look like below format

 ParaName DataType  Value

Textfield1 Textfield2 Textfield3  
TestData1   String     test      Checkbox
TestData2   boolean    true      Checkbox
TestData3   int        3         Checkbox

Button   Button
Save     Delete

DATABASE

ParaName|DataType|Value
TestData1|String  |test
TestData2|boolean |true 
TestData3|int     |3

Thanks, Suba

Problem when i push RoR 3 project to Heroku

i am a beginner of RoR Developer, I have finished develop my app and want to try to host in Heroku. I have followed the instruction from this link but when i pushed, it end with error "Precompiling assets failed"

The error log is :

   rake aborted!
   Sass::SyntaxError: Invalid CSS after "}": expected selector or at-rule, was "{"version":3,"s..."
     (in /tmp/build_9248b9568679e374d00011e249821515/app/assets/stylesheets/application.css)
   (sass):3915

Full Log : https://ideone.com/x0Dp2z

My Repository : https://github.com/iamkevinhuang/covid/

vendredi 29 mai 2020

Access routes in ruby after logged in

I am beginner in ruby. I have routes in routes.rb like: get 'users/edit/:id'. I made a login route as well.

I want to check if someone is logged in before he access a route, so if we try to access get 'users/edit/:id' without logged in we will redirect to the login screen.

How can i do that? I think I should write something after the routes to check if the user is logged in, but i dont know the syntax. Thx for the answers

vendredi 22 mai 2020

Rails 3: Given a player, find the number of times they have been paired with each opponent

I am using Rails 3.2. My schema is quite more complex but simplifying, I have Pcs (representing players), Games and Projects such that:

class Game < ActiveRecord::Base
   has_many :projects

class Pc < ActiveRecord::Base
   has_many :projects

class Project < ActiveRecord::Base
   has_many :games
   belongs_to :pc

note: there's a table for GameProject as well for the many-to-many association.

I am trying to find a query (ActiveRecord is preferred over fully raw SQL) such that, given a Pc, returns the number of games each one of the other Pcs has played against them. A Pc has played against another one if there are project(s) of the two of them in the same game. An example situation would be:

+------+---------+----+
| Game | Project | Pc |
+------+---------+----+
|    1 |       1 |  1 |
|    1 |       2 |  1 |
|    1 |       3 |  1 |
|    1 |       4 |  2 |
|    1 |       5 |  2 |
|    2 |       6 |  1 |
|    2 |       7 |  2 |
|    3 |       8 |  1 |
|    3 |       9 |  3 |
+------+---------+----+

If I want to find out how many times each opponent has played against Pc1, the result should be:

{2 => 2, 3 => 1}

As Pc2 has played in two games with Pc1 and Pc3 has played only once with Pc1. I don't care if Pc1 itself appears in the result, I'll just not process it afterwards.

The same query for Pc2 should return:

{1 => 2, 3 => 0}

As Pc1 has played twice with Pc1 and Pc3 has not played in any game with Pc2.

I've been trying for a while but I can't seem to get it right.

Thanks in advance!

jeudi 21 mai 2020

Can array elements be attribute readers in ruby?

I have a class with one of the input parameters to the constructor an array:

class MyClass
  def initialize(types: types)
    @types = types  #types in an array
  end
  attr_reader :types

  def some_func
   types.each do { |type| do_something(type) }
  end

  def do_something(type)
    call1(type)
    call2(type)
    call3(type)
  end
end

Basically, I want to avoid using type as a function argument since it is being used for so many function calls. is there a way I can make it an attribute and avoid having to use it as a argument to so many function calls?

Thanks!

mercredi 20 mai 2020

Undefined method `shift' for "b":String (NoMethodError) Ruby

I keep getting the same error when trying to run this method that translates a string into pig latin.

def pig_latin_word(word)
  new_arr = []
  letter = word.split("")

    if letter[0] == "a" || letter[0] == "e" || letter[0] == "i" || letter[0] == "o" || 
      letter[0] == "u"
      new_arr << "yay"
    else
      letter[0].shift && new_arr << letter[0].push + "ay"
    end
  return new_arr.join

end

Test cases: 
puts pig_latin_word("eat")     # => "eatyay"
puts pig_latin_word("banana")  # => "ananabay"
puts pig_latin_word("trash")   # => "ashtray"

ActionView::Template::Error: Can't resolve image into URL: undefined method `[]' for nil:NilClass

using: Ruby 2.4.0p0 Rails 5.2.3 while running my test cases: having and error:

My testcase is like:

require 'test_helper'

class SubscriptionsControllerTest < ActionDispatch::IntegrationTest

  test "Can reach to index " do
    get subscriptions_url
    assert_response :success
  end

end

Error:

SubscriptionsControllerTest#test_Can_reach_to_index_:
ActionView::Template::Error: Can't resolve image into URL: undefined method `[]' for nil:NilClass
    app/views/subscriptions/index.html.erb:43:in `_app_views_subscriptions_index_html_erb__900758959545617488_70234463713200'
    test/controllers/subscriptions_controller_test.rb:6:in `block in <class:SubscriptionsControllerTest>'

But the image load correctly when open the ui manually. could you suggest what is wrong.

lundi 18 mai 2020

To get IP addres of the specific host machine in rub

I want to find the ip address of other system. For example:- i am executing my code from server wevrs1234 and i want ip address of server apvrs1234 and store it in variable. Please help me to get this.

Syntax error, unexpected ',', expecting keyword_end arr.each_with_index |ele1, idx1|

Get the following error when testing this method.

def opposite_count(nums)
pairs = []
    arr.each_with_index |ele1, idx1|
        arr.each_with_index |ele2, idx2|
            if (idx2 > idx1) && (ele1 + ele2 == 0)
              pairs << ele1
            end
        end 
    end
    return pairs.length
end

Goal is to take in an array of unique numbers and return the number of pairs of elements that sum to 0.

The other errors that show up are:

syntax error, unexpected ',', expecting keyword_end
        arr.each_with_index |ele2, idx2|

and

 syntax error, unexpected keyword_end, expecting end-of-input

Rails: switch to puma for request specs

We are working on a rails 3.2 app with RSpec 3.7 and want to use puma as web server for our rails request specs.

We know we can switch the server for Capybara feature specs using

Capybara.register_server :puma

But how can we switch the server for request specs?

Background:

We want to spec concurrency issues and need our test server to actually process requests parallelly.

dimanche 17 mai 2020

Association in rails Model

Below is the model Structure.

class JobFamilyRole < ActiveRecord::Base
   belongs_to :JobFamily
   belongs_to :JobRole
   belongs_to :Organization
end

class JobFamily < ActiveRecord::Base
   has_many :JobFamilyRoles
   has_many :JobRoles
end

I am looking for below result from the above JobFamilyRole table.

  {
     job_family1: [job_role1, job_role2],
     job_family2: [job_role1, job_role2, job_role3]
     ...
  }

I achieved this Result from below query:

  job_family_roles = JobFamilyRole.where(:organization_id => org_id)
  results = {}
  job_family_roles.each do |job_family_role|
    job_family = JobFamily.find(job_family_role.job_family_id)
    result[job_family.name] = job_family.job_roles.collect(&:title)
  end

 puts results 

But Above query doesn't look optimized one so can anyone help me to write the optimized query. In our App org_id is present.

samedi 16 mai 2020

The 2nd assignment of the 1st course from the Rails Specialization in Coursera

The overall goal of the assignment is to write a Ruby class and work with attributes, methods, hashes, and arrays. The functional goal of the assignment is to read some text from a file and find the word or words that appear the most in a line in the file. The way we are instructed to measure “the words that appear the most” is by 1. finding the highest frequency word(s) in each line 2. finding lines in the file whose "highest frequency words" is the greatest value among all lines.

Syntax error, unexpected tIDENTIFIER, expecting ')' Ruby

I get the following error when running a simple method that takes in a proper noun string and returns the string properly capitalized.

def format_name(str)
    parts = str.split
    arr = []
    parts.map do |part|
      if part[0].upcase
      else part[1..-1].downcase
      arr << part
      end
    end
 return arr.join(" ")
end

Test cases: puts format_name("chase WILSON") # => "Chase Wilson" puts format_name("brian CrAwFoRd scoTT") # => "Brian Crawford Scott"

vendredi 15 mai 2020

`initialize': wrong number of arguments (given 0, expected 2) (ArgumentError)

class LineAnalyzer

 @@highest_wf_count=[]
 @@highest_wf_words=[]
 attr_accessor :highest_wf_count ,:highest_wf_words ,:content , :line_number


 def  initialize(line,num)
        @content=line
        @line_number=num
        calculate_word_frequency(@content,@line_number).call
 end

 def calculate_word_frequency(con,num)
        @content,@line_number=con,num
        @arr= @content.split()

       @arr.map do |txt|
               @count=0
               @i=0
               while @i<@content.length
                    @count+=1 if txt.eql?(@arr[@i])
                    @i+=1
               end
               @@highest_wf_count[@line_number]= @count
               @@highest_wf_words[@line_number]= txt
               @arr.delete(txt)
       end 
  end
end

class Solution < LineAnalyzer

 attr_accessor :analyzers, :highest_count_across_lines, :highest_count_words_across_lines

def initialize
       @analyzer=[]
       @highest_count_across_lines=0
       @highest_count_words_across_lines=[]
end

def analyze_file()
        @arr=IO.readlines(ARGV[0])
        @analyzers=Array.new(@arr.length){LineAnalyzer.new}
        @i=0
        @analyzer.each  do |obj|
                obj(@arr[@i],@i)
                @i+=1
        end
end

def calculate_line_with_highest_frequency()
     @highest_count_across_lines = @@higest_wf_count.max
     @i=0
     @@highest_wf_count.each do |count|
            @highest_count_words_across_lines.push @@highest_wf_words[@i]  if count==@highest_count_across_lines
            @i+=1
     end
 end
  • The above code is to calculate word frequency in a text file
  • Whenever I try to run this below command I get the following error int the intialize function in LineAnalyzer class

ruby module2_assignment.rb test.txt

Error : `initialize': wrong number of arguments (given 0, expected 2) (ArgumentError)

Since I amm a rookie in ruby I can't figure out the error. Please help me out. Thanks in advance!!!

mercredi 13 mai 2020

Ruby block `block in Method': undefined method `inject' for true:TrueClass (NoMethodError)

I have a method that takes in a string and returns a new sentence string where every word longer than 4 characters has all vowels removed. The output should return a modified sentence string to these specs.

def abbreviate_sentence(sent)
  arr = []
  word = sent.split("")
  word.reject do |v|
       if word.length > 4
         arr << %w(a e i o u).any?.inject(v)
       else arr << word
       end
  end
  return arr
end

I get the following error and am trying to include/"inject" the modified elements into a new array in which to join into the desired string described above. If I remove "inject" I get a boolean and not the modified string.

How to avoid assets pre-compilation in Rails with React JS?

I am new to "React JS" and I am trying to implement some functionalities in my rails project. Whenever I do any changes in my assets code, It needs pre-compilation. Then it will be apply my code. Is there any way I can see my code changes directly or without pre-compilation.

mardi 12 mai 2020

Thread.list won't show thread with websocket in it randomly

I can't figure out one thing. I'll explain step by step.

Using ruby 2.1.5p273, rails 3.2.13 and nginx (latest) on production server.

With one request i am starting websocket in new thread as follows:

main_thread = Thread.new {

   main_thread.thread_variable_set(:foo, 'foo')
   main_thread.thread_variable_set(:bar, 'bar')

   EM.stop if EM.reactor_running?
   EM.run {
      ws = Faye::WebSocket::Client.new(...)
      ws.on :open {...}
      ws.on :message {...}
      ws.on :close {...}
   }

   main_thread.thread_variable_set(:ws, ws)
}

Then with another request, if i wish, i want to close websocket on demand as follows:

Thread.list do |thread|
   if thread.thread_variable_get(:foo) == 'foo' && thread.thread_variable_get(:bar) == 'bar'
      thread.thread_variable_get(:ws).close

      sleep 1

      thread.exit
   end
end

What buggers me is a fact, sometimes i can't list main_thread in Thread.list even tho i see it is active in logger. Most of the time, it works ( i can list and exit it ). What i do when i can't? I F5 the page and try it with another request ( click the button again). Sometimes it doesn't work on the first F5 refresh, but eventually it works. I was unable to search anything about invisible thread or so. Is there any filter Thread.list won't show all of running threads in application?

What is the catch ?

Any insight is most welcome.

dimanche 10 mai 2020

how to combine rescue multiple exceptions in ruby on rails?

is it possible to combine multiple rescue statements into one in ruby on rails.

begin
   //do something 
  rescue ArgumentError => e
      e.message
  rescue NameError => e
      e.message
  rescue StandardError => e
      e.message
end

combined to something like below

rescue ArgumentError, NameError, StandardError => e
      e.message

samedi 9 mai 2020

Can someone please let me know where i was wrong. why am i not getting the right answer

Given two strings, word and key, how can I write a method sequence_search(word, key) that returns true (else false) if the characters in key appear in the same order (but not necessarily contiguous) in word?

def sequence_search(word, key)
       new = key.chars
        arr = []
        i = 0
        while i < word.length
        if word[i].include?(key)
        arr >> word[i]
          end
          i+= 1
          end
            if arr.join == key  # line raising exception
            return true
          end
          return false
          end
        end
    sequence_search("arcata", "cat") #=> true
    sequence_search("c1a2t3", "cat") #=> true
    sequence_search("cta", "cat")    #=> false
    sequence_search("coat", "cat")   #=> true

jeudi 7 mai 2020

Rails - Object in has_many relation is not getting updating

I am having a table called Groups, where Groups and Sub-Groups are saved. A group has_many sub-group. Below is the code

groupone.rb (one of the main group)

class GroupOne < BaseGroup
  belongs_to :parent, class_name: 'GroupOne'
  has_many :sub_group_one, autosave: true, dependent: :destroy, inverse_of: :groupone
end

reports_controller.rb

class ReportsController < ActionController::Base

  def process_report
    current_record = load_from_xml(xml_path)
    current_group = current_record.last
    base_report_group = find_or_create_base_group(current_group)
    process_sub_group(current_group, base_report_group)
    base_report_group.save

  end

  def process_sub_group(current_group, base_report_group)
    if current_group.sub_group_one.present?
      current_group.sub_group_one.each do |sub_group|
        sgroup = base_report_group.sub_group_one.find_or_initialize_by(group_type_id: sub_group.group_type, serial_num: sub_group.serial_num)
        sgroup.attributes = {name: "Rob", age: 12}
      end
  end

end

The above code is creating new GroupOne and many sub_group_one records with out any issues but when i try to update the existing sub_group_one values, they are not getting updated. For example {name: "Rob", age: 12} is not getting updated to any of the sub-group record. I noticed that the new attributes are assigned to sgroup during the current sub_group iteration and once all the sub_group iteration are completed, when i do binding.pry for base_report_group.sub_group_one it shows the old record and this is the issue.

Can any one please help me to fix this. Thank you

How to use form_tag with "get" method

I'm trying to use form_tag with get method but it become a post method

<%= form_tag(:method => "get", :room => @room.id) do %>
  <%= label_tag("Vote for:") %>
  ..some thing else..
  <%= submit_tag("Vote") %>
<% end %>

this is my code but if i inspect elemen, it was become :

<form accept-charset="UTF-8" action="/start/testing?method=get&amp;room=43" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="j4fgdRYJXeyQfmnqMQNFb2fYuw2+/UXRw1UFxc0WuHo=" /></div>
  <label for="Vote_for:">Vote for:</label>
  ..some thing else..
  <input name="commit" type="submit" value="Vote" />
</form>

I think i become a parameter, how can I fix it ? Thank you

mercredi 6 mai 2020

Rails 4 Sprockets : No such file

I'm currently in the middle of upgrading a Ruby on Rails 3 project to Ruby on Rails 4.0. Several of my tests related to controllers are failing because specific files cannot be found when rendering the templates during the tests:

ActionView::Template::Error: No such file or directory

All these errors have the same in common, that they try to load files from the tmp/cache in the Rails application. This was working all fine under Rails 3. Is something specific required for asset compilation under Rails 4 in tests?

# config/application.rb
# Enable the asset pipeline
config.assets.enabled = true

The above is not overwritten in our test environment, so I assume this remains enabled? And we used Sprockets in Rails 3 as well.

  • Rails : 4.0
  • Sprockets : 3.6

I'm probably missing something obvious, just can't find it...

Error output

test_0001_should show a form to upload attachments and display existing ones(AttachmentsControllerTest::#new):
ActionView::Template::Error: No such file or directory @ rb_sysopen - /root/rails_backend/tmp/cache/assets/test/sprockets/v3.0/m7/m7YIr0duEvKhRldOP5LjpABJF7kd9H6aT5dCMyGnOl8.cache.47262198725000.3291.4516
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:278:in `initialize'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:278:in `open'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:278:in `atomic_write'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/cache/file_store.rb:107:in `set'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/cache.rb:212:in `set'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/cache.rb:86:in `fetch'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/base.rb:56:in `file_digest'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/unloaded_asset.rb:104:in `dependency_history_key'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:304:in `fetch_asset_from_dependency_cache'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:44:in `load'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/cached_environment.rb:20:in `block in initialize'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/cached_environment.rb:47:in `yield'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/cached_environment.rb:47:in `load'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/base.rb:66:in `find_asset'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/environment.rb:30:in `find_asset'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-3.7.2/lib/sprockets/base.rb:92:in `[]'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-rails-2.3.3/lib/sprockets/rails/helper.rb:123:in `asset_digest_path'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-rails-2.3.3/lib/sprockets/rails/helper.rb:76:in `compute_asset_path'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/asset_url_helper.rb:132:in `asset_path'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-rails-2.3.3/lib/sprockets/rails/helper.rb:91:in `asset_path'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/asset_url_helper.rb:234:in `javascript_path'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/asset_tag_helper.rb:58:in `block in javascript_include_tag'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/asset_tag_helper.rb:56:in `map'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/asset_tag_helper.rb:56:in `javascript_include_tag'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/sprockets-rails-2.3.3/lib/sprockets/rails/helper.rb:148:in `javascript_include_tag'
    /root/rails_backend/app/views/layouts/attachments.html.erb:2:in `block in _app_views_layouts_attachments_html_erb___457563631613762413_47262336759680'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/capture_helper.rb:38:in `block in capture'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/capture_helper.rb:200:in `with_output_buffer'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/haml-4.0.7/lib/haml/helpers/action_view_xss_mods.rb:5:in `with_output_buffer_with_haml_xss'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/capture_helper.rb:38:in `capture'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/haml-4.0.7/lib/haml/helpers/action_view_mods.rb:52:in `capture_with_haml'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/helpers/capture_helper.rb:152:in `content_for'
    /root/rails_backend/app/views/layouts/attachments.html.erb:1:in `_app_views_layouts_attachments_html_erb___457563631613762413_47262336759680'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/template.rb:143:in `block in render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/notifications.rb:159:in `block in instrument'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/notifications.rb:159:in `instrument'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/template.rb:141:in `render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/renderer/template_renderer.rb:47:in `render_template'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/renderer/template_renderer.rb:17:in `render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/renderer/renderer.rb:42:in `render_template'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_view/renderer/renderer.rb:23:in `render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/abstract_controller/rendering.rb:127:in `_render_template'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/streaming.rb:219:in `_render_template'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/abstract_controller/rendering.rb:120:in `render_to_body'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/rendering.rb:33:in `render_to_body'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/renderers.rb:26:in `render_to_body'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/abstract_controller/rendering.rb:97:in `render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/rendering.rb:16:in `render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/instrumentation.rb:41:in `block (2 levels) in render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
    /usr/local/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/core_ext/benchmark.rb:12:in `ms'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/instrumentation.rb:41:in `block in render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/instrumentation.rb:84:in `cleanup_view_runtime'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activerecord-4.0.13/lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/instrumentation.rb:40:in `render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/implicit_render.rb:10:in `default_render'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/implicit_render.rb:5:in `send_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/abstract_controller/base.rb:189:in `process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/rendering.rb:10:in `process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/abstract_controller/callbacks.rb:18:in `block in process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/callbacks.rb:453:in `_run__64868443609262235__process_action__callbacks'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/callbacks.rb:80:in `run_callbacks'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/abstract_controller/callbacks.rb:17:in `process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/rescue.rb:29:in `process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/notifications.rb:159:in `block in instrument'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activesupport-4.0.13/lib/active_support/notifications.rb:159:in `instrument'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/instrumentation.rb:30:in `process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/activerecord-4.0.13/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/abstract_controller/base.rb:136:in `process'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/abstract_controller/rendering.rb:44:in `process'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/test_case.rb:572:in `process'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/test_case.rb:64:in `process'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/active_model_serializers-0.9.5/lib/action_controller/serialization_test_case.rb:25:in `process'
    /root/rails_backend/vendor/bundle/ruby/2.2.0/gems/actionpack-4.0.13/lib/action_controller/test_case.rb:472:in `get'
    /root/rails_backend/test/functional/attachments_controller_test.rb:78:in `block (2 levels) in <class:AttachmentsControllerTest>'

Page reload on a form submit! Rails API backend Javascript frontend

I'm having trouble figuring out my javascript. The e.preventDefault() is not working. I've tried changing the submit input to a button as well. I know with a form and using rails that it has an automatic rage reload but I thought e.preventDefault was suppose to stop that. Is there some hidden feature in the backend that I need to turn off? I set my project up to be an api by using an api flag. It also has all the right info for cors. My server is showing my data correctly ...it's just the frontend I cant get up.

I'm going to post a sample code I followed.


<html lang="en" dir="ltr">

  <head>

    <title>Problems</title>

    <meta charset="utf-8">
    <link rel="stylesheet" href="styles.css">
    <script type="application/javascript" src="src/user.js" charset="UTF-8"></script>
    <script type="application/javascript" src="src/problem.js" charset="UTF-8"></script>

  </head>

  <body>

   <div class="container" id="container">

    <h1>Everyone Has Problems</h1>

        <div id="new-user-and-new-problem-container">
            <form id="new-user-form">
                <label>Your name:</label>
                <input type="text" id="new-user-body"/>
                <input type="submit"/>
            </form>
        </div>

    </div>

    <div id="problems-container" class="problems-container">
    </div>

  </body>

</html>```

src/user.js
```document.addEventListener('DOMContentLoaded', function(){
    User.createUser()
})

class User {

    constructor(user){
        this.id = user.id
        this.name = user.name
        this.problems = user.problems
    }

    static createUser(){
        let newUserForm = document.getElementById('new-user-form')
        newUserForm.addEventListener('submit', function(e){
            e.preventDefault()
            console.log(e);
                fetch('http://localhost:3000/api/v1/users', {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "Accept": "application/json"
                    },
                    body: JSON.stringify(
                        {
                            user: {
                                name: e.target.children[1].value
                            }
                        })
                    })
                        .then(resp =>  {
                            return resp.json()
                        })
                        .then(user => {
                            let newUser = new User(user)
                            newUser.displayUser()
                        })
        })
    }

    displayUser() {
        let body = document.getElementById('container')
        body.innerHTML = ''
        let userGreeting = document.createElement('p')
        userGreeting.setAttribute('data-id', this.id)
        let id = userGreeting.dataset.id
        userGreeting.innerHTML = `<h1>Hey, ${this.name}!</h1>`
        body.append(userGreeting)
        if (this.problems) {
            this.problems.forEach(function(problem){
                let newProblem = new Problem(problem)
                newProblem.appendProblem()
            })
        }
        Problem.newProblemForm(this.id)
    }

}```

src/problem.js
```class Problem {

    constructor(problem){
        this.id = problem.id
        this.name = problem.name
        this.description = problem.description
    }

    static newProblemForm(user_id) {
        let body = document.getElementById('container')
        let form = 
            `
                <form id="new-problem-form">
                    <label>What's your problem?:</label>
                    <input type="text" id="problem-name"/>
                    <label>Describe it:</label>
                    <input type="text" id="problem-description"/>
                    <input type="submit"/>
                    <h4>Your current problems:</h4>
                </form>
            `
        body.insertAdjacentHTML('beforeend', form)
        Problem.postProblem(user_id)
    }

    //is it appropriate for this to be a static method?
    static postProblem(user_id) {
        let newForm = document.getElementById('new-problem-form')
        newForm.addEventListener('submit', function(e){
            e.preventDefault()
            fetch('http://localhost:3000/api/v1/problems', {
                method: "POST",
                headers:{
                    "Content-Type": "application/json",
                    "Accept": "application/json"
                },
                body: JSON.stringify(
                    {
                        problem: {
                            name: e.target.children[1].value,
                            description: e.target.children[3].value,
                            user_id: user_id
                        }
                    }
                )
            })
            .then(resp => resp.json())
            .then(json => {
                let newProblem = new Problem(json)
                newForm.reset()
                newProblem.appendProblem()

            })
        })
    }

    appendProblem(){
        let problems = document.getElementsByClassName('problems-container')
        let li = document.createElement('li')
        li.setAttribute('data-id', this.id)
        li.setAttribute('style', "list-style-type:none")
        li.innerHTML = `${this.name} ~~ ${this.description}`
        let solveForm = `<button type="button" id="${this.id}" class="solve-problem"> Solve </button>`
        li.insertAdjacentHTML('beforeend', solveForm)
        problems[0].append(li)
        let button = document.getElementById(`${this.id}`)
        this.solve(button)
    }

    solve(button){
        button.addEventListener('click', function(e){
            e.preventDefault()
            fetch(`http://localhost:3000/api/v1/problems/${e.target.parentNode.dataset.id}`, {
                    method: "DELETE"
            })
                    e.target.parentElement.remove();
        })
    }

}```

PHP within a ruby on rails application?

I have an unusual question.

I want to display a php file page within my ruby on rails application. So i want to put it in some random directory and under https://ift.tt/3b6cGhd there should be just a independent file.

I don't get how i can do this, since everything has to be connected via routes.

Is this even possible?

mardi 5 mai 2020

undefined method `id' for nil:NilClass in rails

I am creating instagram app from https://medium.com/luanotes/build-instagram-by-ruby-on-rails-part-2-d70b44f5c7e6.

Under this topic: Add a form to create a new Post in Homepage

I am getting this error : undefined methodid' for nil:NilClass`

my index view file

<%= form_for Post.new do |f| %>
  <div class="form-group">
    <%= f.text_field :description %>
  </div>
  <div class="form-group">
    <%= f.file_field :image %>
  </div>
  <div class="form-group">
    <%= f.text_field :user_id,nil, value: current_user.id, class:'d-none'%>
  </div>
  <br>
  <div class="text-center">
    <%= f.submit 'Create Post', class: 'btn btn-primary' %>
  </div>
<% end %>

Controller file:

class PostsController < ApplicationController
    def create
        Post.create(post_params)

        redirect_to root_path
    end

    private

    def post_params
        params.require(:post).permit(:description, :image, :user_id)
    end
end

lundi 4 mai 2020

Rails + Memcachier shows missing key

I am using memcachier in my rails applciation which is running in Heorku, below the gem details

memcachier (0.0.2)

dalli (2.6.2)

Ruby 1.9.3

Rails 3.2.11

Let say I am rendering a file called _credit_account.html.erb and in the file I am using a caching mechanisam to store the user details, code looks like

def credit_account

end

In the partial _credit_account.html.erb

Rails.cache.fetch(
"user_details_of_credit_account_#{account_id}"
) do
UserDetails.for_account(account_id).to_a
end

So in the dashboard of MemCachier I can see the hit for this key

GET OK 5KB user_details_of_credit_account_53625762

But the strange thing is I can see this missed key also for the whole page,

GET Key not found http://sample.app.com/user/credit_account?id=53625762

This looks like I am using the whole page caching but there is no code other than this. Am i missing anything here?

dimanche 3 mai 2020

Ruby: merge three array of hashes in different way

I'm new to Ruby and trying to build a meeting app. I have three arrays containing hashes :

  • one containing my scheduled meetings with dates and therefore an empty array of people
  • one containing the people invited per meeting
  • and a last one containing the people who refused

This materializes as:

meetings = [
 {:id=>"1", :peoples=>[]}
 {:id=>"2", :peoples=>[]}
 {:id=>"3", :peoples=>[]}
]

invited_peoples = [
 {:id=>"1", :peoples=>['Tom', 'Henry', 'Georges', 'Nicolas']}
 {:id=>"2", :peoples=>['Arthur', 'Carl']}
]

absent_peoples = [
 {:id=>"1", :peoples=>['Henry', 'Georges']}
]

And I would like to have : meetings + invited_peoples - absent_peoples like

meetings_with_participants = [
 {:id=>"1", :peoples=>['Tom', 'Nicolas']}
 {:id=>"2", :peoples=>['Arthur', 'Carl']}
 {:id=>"3", :peoples=>[]}
]

I'm looking for a readable solution but I don't find anyone...

Sorry for my english and thank you in advance, Nicolas