jeudi 30 septembre 2021

Difficulty installing rails on Mac Mojave

I am trying to install rails using bash and it will install, however when I go to check the version it says that rails has not been installed. If I locate rails it finds it in my Homebrew directory. I downloaded the rbenv manager too but when I -v I don't get my latest version. If I try to run a rails command it just says rails is not installed on my system.

Short of deleting everything, I've tried to update all the necessary components. One thing I think is happening is that my file pathways are all mixed up. However, I am brand new to programming and seriously have no idea what I'm doing. Please help.

mardi 28 septembre 2021

How to query the active record filtering by date?

How can I select ALL student students from my database with active status only in the month of May? I couldn't find it in the active record documentation. I only managed to query the students who were created in May, and not ALL students actived....

Student.where(status:'active', created_at: ('2021-05-01'..'2021-05-31')).count

actually, my idea would go something like this:

Student.where(status:'active', datetime: (('2021-05-01'..'2021-05-31')).count

Storext custom fields dinamically

i have this store_attributes using Storext.model in my column jsonb data

store_attributes :data do
  name String
  user String
  password String
  type String
end

i don't need the last field type for my custom fields but i need for use class. some tip?

i'm calling like this in view

stored_attributes[:data].each do |accessor|
= f.input accessor

but i don't need type field

jeudi 23 septembre 2021

Rails - Why is this rolled back after a deadlock is detected in MySQL?

I have the following code in which a deadlock exception is rescued. In that rescue, I modify another record and save it. That save doesn't go through.

Is a transaction within rescue a nested transaction of the transaction in the begin?

begin
  Something.transaction do
    something.save # this causes a deadlock
  end

rescue StandardError => se
  # This gets called while rescuing a deadlock
  some_record.status = "updating"
  some_record.save # this seems to get rolled back
  puts se.error_message # Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction:
end

WiceGrid Export Failing

I have Student Table which has more than 15 million records, I am trying to export the data with the WiceGrid export CSV option, but it often timeouts.

What should I do to avoid timing out and giving me the CSV file correctly?

Controller Function

def index
  @students_grid = initialize_grid(
    current_school.students,
    order: 'students.id',
    order_direction: 'desc',
    per_page: 100,
    name: 'g1',
    enable_export_to_csv: true,
    csv_file_name: 'students-' + Time.current.to_s(:number)
  )

  export_grid_if_requested('g1' => 'students_grid') do
  end
end

mercredi 22 septembre 2021

echo 'eval "$(rbenv init -)"' >> ~/.zshrc not appending zshrc file

I am trying to install Ruby on Rails on OSmac Big Sur.

I have installed Xcode and brew

% gcc --version Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1 Apple clang version 12.0.0 (clang-1200.0.32.29) Target: x86_64-apple-darwin20.5.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

% brew -v

Homebrew 3.2.13-4-gbefaeba

I also have installed ruby, rbenv and Rails

% ruby -v
ruby 2.6.3p62 (2019-04-16 revision 67580) [universal.x86_64-darwin20]

% rbenv -v
rbenv 1.1.2

% rails -v
Rails 6.1.4.1

'rbenv init' gives me the following

 % rbenv init 
# Load rbenv automatically by appending
# the following to ~/.zshrc:

eval "$(rbenv init -)"

I tried

echo 'eval "$(rbenv init -)"' >> ~/.zshrc

which gives

quote>

and

% echo ''eval "$(rbenv init -)"' >> ~/.bash_profile

which gives

quote>

Why is echo 'eval "$(rbenv init -)"' >> ~/.zshrc not appending the file zshrc as expected?

vendredi 17 septembre 2021

How can show only those user who is not linked with project in rails

I am trying to show only those developers who are not linked with project but it always show one developer who is already linked

ProjectDeveloper is model which have project and developer id User have a column user type which type is enum who contain developer manager and qa

controller

 def index

    @users = User.where(user_type: 'Developer')
    @project_developer = ProjectsDeveloper.where.not(id: @users.ids)
    project_id = params['project_id'].to_i
    @project_id = Project.find(project_id)
 end

html.erb

<% @project_developer.each do |user| %>
   <h3><%=user.developer_id %></h3>

   <%=button_to 'Assign' , projects_developer_index_path({project_id: @project_id.id, developer_id: user.id}),
         method: :post %><br>
<% end %>

jeudi 16 septembre 2021

Add parameter to all urls in rails

I am working on improving a project where currently we have a user status parameter stored in session. However, I would like to move status out of the session, as I don't want this status to be affected by different tabs from the same users. So my proposal is like I need to add the status to the end of the URL like

htttp://example.com/index/?status=0

I already have a before_action for the application controller to read status like below

 def set_status
    if params[:status]
       @status = params[:status]
    else
       @status = 0
    end
 end

Previously, when I stored the status in the session, the before action was more like below

 def set_status
    if session[:status].nil?
       session[:status] = 0
    end
    @status = session[:status]
 end

But I don't know what to do to add /?status=0 for all URLs I have in the project and keep it unchanged from one page to another unless the user changes it. As it is a very large and complicated project, I don't think I can go to every view or controller action to manually add it one by one. So I am wondering if there is an elegant solution to it.

How can show the drop down value against the enum value

status is a drop down having values (new, started, completed) if it’s a feature or (new, started and resolved) if it’s a bug. I don't know how can i do this

Model

Class Task
  enum typeOf: %i[feature bug]
  enum status_is: %i[New started completed resolved]
end

erb.html

<%= form_for :task, url: project_tasks_path, :html => {:multipart => true, :cla

   <%= f.hidden_field :project %>
   Title: <%=f.text_field :title, class:"form-control" %><br>
   Description: <%=f.text_field :description, class:"form-control" %><br>
   <label for="deadline">Deadline</label><input type="datetime-local" id="deadline"
                                         name="deadline" ><br>
   Screen Shot: <%=f.file_field :screen_shot, multiple: true, class:"form-control" %>
   <div class="field">
     <%= f.label :typeOf, class:"form-control" %><br />
     <%= f.select(:typeOf, Task.typeOfs.keys.map {|role| [role.titleize,role]}) %>
   </div>

   <div class="field">
     <%= f.label :status_is, class:"form-control" %><br />
     <%= f.select(:status_is, Task.status_is.keys.map {|role| [role.titleize,role]}) %>
   </div>
   <%= f.submit "Add" %>

<%end %>

how can create relation with has many through in rails

I have 3 model User Project Bug. I want to create many to many relation with through. I create the relation in model i don't know it is correct or not, user have user type column which is enum type user type contain developer, manager , QA

user.user_type.manager belong to many project it has one to many relation 
user.user_type.developer has many project and many project belong to developer. it has many to many realtion 

project has many bugs and bugs belong to project 

developer has many bugs and many bugs belong to developer

bug model

class Bug < ApplicationRecord
   belongs_to :project
   has_many :developers, -> { where user_type: :Developer }, class_name: 'User', through: :project, source: :bugs

end

project model

class Project < ApplicationRecord
   has_many :bugs, dependent: :delete_all
   has_many :developers, -> { where user_type: :Developer }, class_name: 'User', through: :users, source: :project
   has_many :users  //it belong to manager_id
end

user model

class User < ApplicationRecord

   enum user_type: %i[Manager Developer QA]  
   has_many :projects
   has_many :bugs
end

developer_bug model

class DevelopersBug < ApplicationRecord
  has_many :bugs
  has_many :users
end

project_developer model

class ProjectsDeveloper < ApplicationRecord
  has_many :projects
  has_many :users
end

mercredi 15 septembre 2021

How can get the selected option id in rails

I am trying to get the id of selected option from dropdown but i get the nill id when i create the project

def create


    developer_id = params[:developer_id]
    parameters = project_params.merge({ user_id: current_user.id, developer_id: developer_id })
    @project = Project.new(parameters)
    respond_to do |format|
      if @project.save
         format.html { redirect_to projects_path, flash: { success: 'Project added successfully ' } }
      else
         format.html { render :new }
      end

   end
end

def project_params
   params.require(:project).permit(:name, :user_id)
end

new.html.erb

 <%= form_for :project, :html => {:class=>"form-group"}, url: projects_path  do |f| %>

   Add task: <%=f.text_field :name, class:"form-control" %><br>
   <h2>Select Developer</h2>
   <%= f.select :developer_id, options_for_select(@users.collect  {|user|["#{user.name}","#{user.id}"]}) %><br>


   <%= f.submit "Add" %>

<% end %>

samedi 11 septembre 2021

how can update the value of null column in rails

I am trying to create multiple bug against one project, but it show the error in edit_task_params

  param is missing or the value is empty: project

when i create the project the bug_id is null i just want to add bug ids against the project but i don't know how can i fix this issue .

project model

class Project < ApplicationRecord
   has_many :bugs
end

bug model class Bug < ApplicationRecord belongs_to :project end

bug_controller

class BugController < ApplicationController
    
    def new
      @bug = Bug.new
    end

    def create

      parameters = bug_params.merge({ user_id: current_user.id })   

      @bug = Bug.new(parameters)
      parameter = edit_task_params.merge({ bug_id: @bug.id })
      @project = Project.find(params[:project_id])
      @project = Project.update( parameter)
      respond_to do |format|
        if @bug.save
          @project = Project.find(params[:project_id])
          @project.update(edit_task_params)
          format.html { redirect_to new_bug_path, flash: { success: "bug added"} }
        else
          format.html { render :new }
        end
      end
   end

 private
 def bug_params
     params.require(:bug).permit(:title, :description, :screen_shot, :typeOf, :status_is, :deadline, :user_id, :project_id )
 end

 def edit_task_params
     params.require(:project).permit(:bug_id)
 end

end

jeudi 9 septembre 2021

Pagy gem not returning the last page records

pagy,records = pagy(Products.all,page: params[:page], items: 5 )

i have total of 10 records. when i request for page 1 records, i get

#<Pagy:0x00007f1dec7cee88 @vars={:size=>[1, 4, 4, 1]}, @count=10, @items=5, @outset=0, @page=1, @last=2, @pages=2, @offset=0, @from=1, @to=5, @prev=nil, @next=2>

but for page 2, it gives

#<Pagy:0x00007faa0c7d0740 @vars={:size=>[1, 4, 4, 1]}, @count=10, @items=0, @outset=0, @page=2, @last=2, @pages=2, @offset=5, @from=6, @to=5, @prev=1, @next=nil>

may be because of from 6 to 5 its not returning me any records.

can someone help with what am i missing?

mercredi 8 septembre 2021

How to add value on current field in devise

Good day ! Im trying to access the fields in my devise

This is my migration file for devise user

 class DeviseCreateUsers < ActiveRecord::Migration[6.1]

    def change
      create_table :users do |t|
        ## Database authenticatable
        t.string :email,              null: false, default: ""
        t.string :encrypted_password, null: false, default: ""
        t.integer :current_points ,default:0
        t.timestamps null: false
    end

 add_index :users, :email,                unique: true
 add_index :users, :reset_password_token, unique: true
 # add_index :users, :confirmation_token,   unique: true
 # add_index :users, :unlock_token,         unique: true
 end

end

I want to be able to add value in current_points field instead of editing it . Im trying to make an app where user can add points from index.html.erb without refreshing the page.

Thanks for the help

URL Structure for Comparing Items

What is the best way to structure a route for comparing multiple items?

Here's the URL example: https://versus.com/en/microsoft-teams-vs-slack-vs-somalia

How to achieve this in routes.rb file? Cannot really find anything in Internet regarding ruby gems. The only thing I can think about is url with optional params, however what if the number of params is unlimited?

mardi 7 septembre 2021

Ruby Array Elements

I am trying to create password Generate in ruby. At the moment all is working just got stuck at the final piece of generating the password.

I asked user if he/she would like the password to include numbers, lowercase or uppercase. If YES, user will enter 1 and 0 for NO.

I used the code below to generate password if everything is 1. Meaning user want to include numbers, lowercase and uppercase.

 if numbers == 1 && lowercase == 1 && uppercase == 1
     passGen = [(0..9).to_a + ('A'..'Z').to_a + ('a'..'z').to_a].flatten.sample(10)
 end

 p passGen

This works 90% of the time. 10% of the time the generated password will not include say any numbers. But everything else present. I am not sure if this is because of the size or length of Array from which the password is sampled.

Anyway lets go to the main problem below

Here is the problem, I am struggling to write the code to generate password if one or more of input is 0. That's if user don't want to include numbers. Or no numbers and uppercase etc . As I can't predict what user may want or not want. I need help on this please. Thank you.

ArgumentError in ImagesController#index / Unknown validator: 'AttachedValidator'

I got this error , while uploading (.cdr) file format

please help me out...

Models/imgae.rb

class Image < ApplicationRecord
   validates :avatar, attached: true

   has_one_attached :avatar

   validates :avatar, attached: true, dimension: { width: { min: 800, max: 2400 } },
   content_type: [:cdr], size: { less_than: 100.kilobytes , message: 'is not given between size' }

     
def self.import(file)
        CSV.foreach(file.path, headers: true) do |row|
          Image.create! row.to_hash
     end
end
end

lundi 6 septembre 2021

How to add text into a image using ruby on rails

How to add text into a image using ruby on rails?

I do have it in excel data . In excel there are Column (order id , order name , etc. ) and I do have a Image Template ..these data should render into the (.CDR) file image..

NoMethodError in ImagesController#import / undefined method `import' for Image:Class

Good Day , I have an error while uploading csv file and also as image uploading into my webpage Error NoMethodError in ImagesController#import undefined method `import' for Image:Class Iam fresher into the ruby on rails plz help me out

Model/image.rb

class Image < ApplicationRecord
   has_one_attached :avatar
     end
def self.import
        CSV.foreach(file.path, headers: true) do |row|
          Image.create! row.to_hash
     end
end

controller/images_controller.rb

 def import
    Image.import(params[:file])
    redirect_to images_path, notice: "excel import successfully"
  end

dimanche 5 septembre 2021

Is it possible to access instance variables from controller to script?

I have this script inside my index.html.erb

<script>
document.getElementById('start-fight').addEventListener('click',function(){

 document.getElementById('player-one-button').disabled = true
  document.getElementById('player-two-button').disabled = true
 number = 5;
  randomNumber = Math.floor(Math.random()*10);

  if (randomNumber < 5 ){
  document.getElementById('amount-bet-for-player-one').innerHTML = "player one wins"
  @lasttransaction.result = "player-one"

  }
  else if(randomNumber > 5){
  document.getElementById('amount-bet-for-player-one').innerHTML = "player two wins"
  @lasttransaction.result = "player-one"
  }
  else{
  document.getElementById('amount-bet-for-player-one').innerHTML = "draw"
  @lasttransaction.result = "draw"
  }
  })     
  </script>

i have this in my index controller

   def index

@transactionhistories = Transactionhistory.all
@battles = @client.getPlayerByPowerstats
@battles2 = @client.getPlayerByPowerstats
@transactionhistory = current_user.transactionhistories.build
@lasttransaction = Transactionhistory.last
@user = current_user.id

end

Im trying to create an app where the user can place his bet to player one or player two . im trying to update the last transaction after i click the fight button . Is it possible to access the controller from script using vanilla javascript ?

jeudi 2 septembre 2021

How can add customer field in devise user table in rails

i am new in ror. I am trying to add two column in devise user table it show the error in html page i don't know how can i fix this issue. I am follow the youtube tutorial i don't know how but his code wrok perfectly and my code showing error. I even add the fields in migration file and run db migrate but nothing change

undefined method `last_name' for #<User id: nil, email: "", created_at: nil, updated_at: nil>

application controller.erb

class ApplicationController < ActionController::Base
   before_action :configure_permitted_parameters, if: :devise_controller?

   protected

   def configure_permitted_parameters
       devise_parameter_sanitizer.permit(:sign_up, keys: [:role_id, :first_name, :last_name])
   end
end

Schema.rb

create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

html

  <h2>Sign up</h2>

  <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>

  <%= render "devise/shared/error_messages", resource: resource %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>

  <div class="field">
    <%= f.label :last_name %><br />
    <%= f.text_field :last_name %>
  </div>

  <div class="field">
    <%= f.label :first_name %><br />
    <%= f.text_field :first_name %>
  </div>


  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
  <%= f.password_field :password, autocomplete: "new-password" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
  </div>

  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
 <% end %>