vendredi 31 juillet 2020

Error starting web application (Bundler::LockfileError)

Try to set up and run canvas-LMS through docker workflow,

Specficicarion: gem version - 3.1.4 ruby version - 2.5.3p105 (2018-10-18 revision 65156) [x86_64-linux] Dory Version: 1.1.0

Steps to reproduce: 1.Clone canvas-LMS repo 2.Run command docker-compose up 3.Browse http://canvas.docker/

PFA enter image description here

mercredi 29 juillet 2020

What is the best way to install ruby/rails on Windows?

I have tried using Ruby Installer but I keep on getting compatibility issues between my ruby version and my rails version.

Mutliple columns of images in table - how to get image url for each one?

I have a table in my rails API called "Visions" and within that table I have 4 columns for images:

  1. image
  2. imagetwo
  3. imagethree
  4. imagefour

I am able to successfully receive image_url of 'image' however I also want to be able to get the url for the remaining 3 image columns.

This is what I have in _vision.json.jbuilder:

json.call(
    vision,
    :id,
    :description,
    :hairdate,
    :products,
    :rating,
    :drying,
    :hairday,
    :styling,
    :created_at,
    :updated_at
)

json.image_url  polymorphic_url(vision.image)

adding json.imagetwo_url polymorphic_url(vision.imagetwo) etc to the end of the code breaks the app and prevents data being sent to my react native front-end.

vision.rb:

class Vision < ApplicationRecord
    has_one_attached :image
    has_one_attached :imagetwo
    has_one_attached :imagethree
    has_one_attached :imagefour
    belongs_to :user

    def featured_image_url
        if self.image.attachment
          self.image.attachment.service_url
        end
      end
end

visions_controller.rb:

    def index
        @visions = current_user&.visions
        render :index, status: :ok
    end

    def new
        @vision = Vision.new
    end

    def create
        @vision = current_user&.visions.create(vision_params)
        render :create, status: :created
    end

    def destroy
        @vision = current_user&.visions.where(id: params[:id]).first
        if @vision.destroy
            head(:ok)
        else
            head(:unprocessable_entity)
        end
    end

    def update
        @vision = current_user&.visions.where(id: params[:id]).first

        if @vision.update(edit_vision_params)
            head(:ok)
        else
            head(:unprocessable_entity)
        end
    end


    private

    def vision_params
        params.permit(:description, :image, :imagetwo, :imagethree, :imagefour, :hairdate, :rating, :products, :hairday, :drying, :styling)
    end
end

vendredi 24 juillet 2020

How can I use Ruby on Rails and Knockout.js in data-bind?

I currently have following codes

<code data-bind="text: xxx, highlightable: true"></code>

And I want to bind something like App::Application::CONFIGURATION[:url] into text of the data-bind

I tried <code data-bind="text: <%=App::Application::CONFIGURATION[:url] %>, highlightable: true"></code> but it didn't work.

Hope that someone can help me solve this problem. I appreciate your help!

mercredi 22 juillet 2020

How can i perform one to one mapping in chef using two array

I have array1 with elements [a1,a2,a3,a4....an] and array2 with elemet [b1,b2,b3,b4....bn] with same number of element. I how i can create a one to one mapping in chef for example (a1 with b1, a2 with b2) further i need to use there two elements for executing curl. Can you help me to figure out how to do this? I want to perform this in chef. I think about this

node[array1].each do |A|
  node[array2].each do |B|
    bash 'Curl Coomad' do
      code <<-EOH
      curl .....
      EOH
    end
  end
end

But this way it will run curl command for each and every member of A and B. But i want to use one to one mapping for running this command for ex a1 from A and b1 from B i want to use it for first execution and second time a2 and B2. Help me to figure this out

mardi 21 juillet 2020

Whenever Cron Job "You must use Bundler 2 or greater with this lockfile. (Bundler::LockfileError)"

I got this error while running my cronjob....

my bundle version is 2.1.4

My Task

bash -l -c 'cd /Users/crone/Project/WEB/rph-web && bin/rails runner -e development "Bill.send_bill_for_payment" >> log/cron.log 2>&1'

My Output

/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/bundler/lockfile_parser.rb:108:in 'warn_for_outdated_bundler_version': You must use Bundler 2 or greater with this lockfile. (Bundler::LockfileError) from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/bundler/lockfile_parser.rb:95:in 'initialize' from /Users/crone/Project/WEB/rph-web/bin/spring:10:in 'new' from /Users/crone/Project/WEB/rph-web/bin/spring:10:in '<top (required)>' from bin/rails:3:in 'load' from bin/rails:3:in '<main>'

lundi 20 juillet 2020

Ruby on Rails - change span tag with input datapicker tag and call a ajax using jquery

I have a span tag

<span id="date_first_collection"><%= date_first_collection %></span>

I want to change this to input datepicker tag when someone clicks on it and if there is a value change then do an ajax call to my controller action else nothing.

def update_date_first_collection
 some code
end

how to do this thing using jquery.

samedi 18 juillet 2020

Dynamic forms with nested attributes in rails

I am using some tutorial to create a dynamic form in which i should be able to add json object array of amounts.

i should get this params from form

quote_amounts: [
  {"kind"=>"website", "label"=>"Website", "amount"=>10000.0}, 
  {"kind"=>"website_review", "label"=>"Website Review", "amount"=>12000.0}
]

I have created created the controller in this way

def create
    @quote.assign_attributes(quote_params)
      if @quote.save
        @quote.submit_quote
        @name = @quote.contact.user.display_name
        redirect_to confirm_form_submission_path
      else
        render :new
      end
  end

and

  def quote_params
    params.require(:vendor_quote).permit(:notes, quote_amounts: [])
  end

and I have created this form

            <%= f.number_field :amount, min: 0, prepend: '$', required: true %>
            <%= f.text_field :label, required: true %>
            <%= f.text_field :kind, required: true %>
            
            <%= f.text_area :notes %>

            <%= f.submit "Submit quote", class: "btn btn-info btn-lg btn-block btn-rounded text-uppercase" %>

by this i am getting this error

undefined method `amount' for :amount

and please tell me that how to add 'add more' button so i can add multiple quote_amounts and save it into one json array object in single form.

vendredi 17 juillet 2020

How can I upload multiple images using Active storage and jbuilder instead of 1 image?

This is what I currently have in my Vision model:

    has_one_attached :image
    belongs_to :user

    def featured_image_url
        if self.image.attachment
          self.image.attachment.service_url
        end
      end
end

in my Vision controller:

    def create
        @vision = current_user&.visions.create(vision_params)
        render :create, status: :created
    end


    def vision_params
        params.permit(:description, :image)
    end

and in _vision.json.jbuilder:

json.call(
    vision,
    :id,
    :description,
    :created_at,
    :updated_at
)

json.image_url  polymorphic_url(vision.image)

I am using Amazon S3 for image storage. How can I change my code to be able to upload multiple image files?

Please also bear in mind that I have existing data in my database where I am getting an image URL for one single Image per Vision. How can I make the changes without affecting my existing database?

Thank you in advance 🙏🏼

Validation to check if algorithem value is correct with input value from user before saving

**when the user click "create new task" , the field "idd" will excetu algorithem and equality with the value by user i.e 202078(2+2+8-7=5), the user should input 5 to create the new task or the task not create **

def show
     @ruby = Task.where(id: params[:id])
     @yearss = @ruby.first.created_at.year.to_s.split(//)
     @yearsss = @ruby.first.created_at.year.to_s
     @monthss = @ruby.first.created_at.month.to_s.split(//)
     @monthsss = @ruby.first.created_at.month.to_s
     @number_id = @ruby.first.id.to_s.split(//)
     @number_ids = @ruby.first.id.to_s
     @iddd = @ruby.first.idd
     @both_odd = (@yearss + @monthss + @number_id).map(&:to_i).select(&:odd?).sum
     @both_even = (@yearss + @monthss + @number_id).map(&:to_i).select(&:even?).sum
     @iddd = (@both_even - @both_odd).abs
     if @iddd  > 9
       (@iddd %= 10).to_s
     else
       @iddd.to_s
     end
     @pardon = (@yearsss + @monthsss + @number_ids + @iddd.to_s)
     @rails = @ruby.first.lname.to_s.slice(0,2) + @ruby.first.name.to_s.slice(0,2) + @pardon
  end
  def new
    @task = Task.new
  end

  def create
    @task = Task.new(task_params)

    respond_to do |format|
      if @task.save
        format.html { redirect_to @task, notice: 'Task was successfully created.' }
        format.json { render :show, status: :created, location: @task }
      else
        format.html { render :new }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

model

class Task < ApplicationRecord
    validates :name, :lname ,presence: true
end

Exclude multi-word keywords from Twitter Search API

I have a list of keywords to be excluded from search here

KEYWORDS = %w[
    covid corona subway railway travel plane brazil ]

exclude = Twitter::KEYWORDS.split(",").join(" -")

and this is how my search query looks like

 json_response = @client.search("(javascript) -#{exclude}", lang: "en", result_type: "recent", tweet_mode: "extended", count: 100)

How can I pass multi-word keywords here to be excluded, for example keywords like "off the hand" or "game plan"?

Adding them along with the other keywords doesn't work as expected.

mercredi 15 juillet 2020

Transforming text to bold in ruby

I have both controller and view for a simple game I've created.

This is my function :

def score
    @letters = params[:letters]
    @word = params[:word].upcase
    if !compsrison?(@word.split(''), @letters.split)
      @result = "Sorry, but #{@word} can't be build out of **#{@letters}**"
    elsif !check_api?(@word)
      @result = "Sorry, but **#{@word}** doesn't seem to be valid English word..."
    else
      @result = "Congratulations! **#{@word}** is a valid English word!"
    end
  end

and simply my view for a result :

 <div class="result">
    <%= @result %>
  </div>

I would like my params[:word] and params[:letters] to be a bold text looking sth like that:1

I can't seem to find the build-in method in ruby for a bold text or change it in my erb file.

thanks!

How to display empty td values which is coming from loop in a table in Rails views

https://i.stack.imgur.com/7M5eg.png

I have to show the images in a table td column. So, I wrote the loop for one td to show at least four images according to uploads. But when images attachments less than 4 another column values shifting to this td column. So, I need to display the empty one also. How to solve it. Here is my code

<% hp.fi_attachments.last(4).each_with_index do |fi,index| %>  
  <td>  
    <div class="image_address">
      <%= image_tag fi.image, :class => "style_image"%>  
    </div>  
  </td>
<%end%>

mardi 14 juillet 2020

`require': libruby.so.1.8: cannot open shared object file: No such file or directory - /app/path/vendor/local/libxml-ruby-2.4.0/lib/libxml_ruby.so

we are trying to upgrade ruby version of our rails application, currently, it's running in ruby 1.8.7 as a initial step trying to upgrade 1.9.2

when we trying to run ./bundle exec rails s we are getting below error

vendor/local/polyglot-0.3.3/lib/polyglot.rb:63:in `require': libruby.so.1.8: cannot open shared object file: No such file or directory - /home/sakthi/Sakthi/trunk_upgrade_v1/vendor/local/libxml-ruby-2.4.0/lib/libxml_ruby.so

but I can see llibxml_ruby.so file that path

NameError: uninitialized constant User on irb console

when writing User.all

However I don't get this error when using rails c

I have only two models:

user.rb

class User < ApplicationRecord
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable
has_many :items end

item.rb

class Item < ApplicationRecord
belongs_to :user end

my gemfile includes

gem 'devise'

I've checked the models and controller names (singular and plural), and restarting the console I've tried running spring stop and didn't fix the issue

Rails 3 throwing NoMethodError for nil:NilClass when using try

The below code is throwing "undefined method `name' for nil:NilClass". I've been trying to understand this but everything I read says that try should never throw a NoMethodError when the receiving object is nil.

is_null = summary.alert_type.try(:name) == :null

lundi 13 juillet 2020

Ruby : Calling method

Hierarchy in which methods are called in ruby : If a method is present in both a/b/c and a/b/c/d directory, what is hierarchy in which they'll be called?

dimanche 12 juillet 2020

How to use find_by_username with case_sensitive: false?

How to use find_by_username with case_sensitive: false?

I explain my issue. I have this script to take the username tagged (after @) and to check if it is a "existing user" or not.

text.gsub! (/@(\S+)/) do |match|
  user = User.find_by_username($1)
    if
    else
    end
  end

In this way if the text is @Mike and the user signed is Mike, it is ok. BUT if the text is @mike and the user signed is Mike, it doesn't work.

Hot to add a case_sensitive false in find_by_username?

vendredi 10 juillet 2020

Not cathing the unicorn timeout exception in heroku

This is sample code which i am trying to handle exception from unicorn.

unicron.rb

worker_processes Integer(ENV['WEB_CONCURRENCY'] || 3)
timeout 15
preload_app true

timeout.rb

Rack::Timeout.timeout = 12

Sample code

def create_store
   ActiveRecord::Base.transaction do

     @store = Store.new(params[:store])
     if @store.save!
       sleep 12.3
       InformUserWorker.perform_async(store_id)
     end

   end

   rescue => exception
    exception.backtrace.each { |trace| puts trace }
   rescue Timeout::Error
    puts 'That took too long, exiting...1'
   rescue Rack::Timeout::RequestTimeoutException
    puts 'That took too long, exiting...2'
   rescue Rack::Timeout::RequestTimeoutError
    puts 'That took too long, exiting...3'
   rescue Rack::Timeout::RequestExpiryError
    puts 'That took too long, exiting...4'
end

I am getting code=H13 desc="Connection closed without response" with this sleep 12.3 seconds, and the transaction rollback happens, but none of these exceptions are executing. I have added couple of exception here. Anything goes wrong here?.

Scope with days period works from the last deploy date

I have a scope on a booking model, that takes bookings into the current period of 15 days. it works, so, in production, after one day i seen that not works, on the log applies the scope filter from the moment deployment was done.

First, scope looked as this:

scope :current_availables, where(date: Date.today..Date.today+14.days )

And now the scope looks like this

scope :current_availables, where(date: Date.current.beginning_of_day..Date.current+14.days )

What is happening?

jeudi 9 juillet 2020

About encoding rails 3

i have 2 application..
first in rails 1 or 2 i think, but another apps in rails 3
apps 1 and 2 is interconected with same database..
in the view on app 1 there is special character "" and it's look normally in view, but in the field of database it turn to "≤"
and when i take that field from database to another app (app in Rails 3), on view it just look same with database "≤"..

How to encode "≤" from database to "≤" on view in rails 3?

Keeping Track of Fields in Active Record/Ruby

If given the following object:

   Animal {
     ......
     owned: true
    }

Is there a way to check if a given animal was owned within a month? Specifically, is there a way to check when the owned field was changed to false/true via Active record?.

Or would I need to set up a separate object that tracks that field's history?

Store AJAX parameters in URL (Rails)

I was already able to replace the posts using AJAX upon submitting the form. The problem though, is that the URL is not updating to include the params I added.

When I click on Submit, the values are passed to the controller. I can call params[:tags] and it will return the IDs. However, the URL is still localhost:3000/posts/:id and it didn't include the tag_ids.

Here are the affected files:

posts_controller.rb:

def show
  @posts = get_posts

  respond_to do |format|
    format.js
    format.html
  end
end

posts/show.html.haml:

#posts
  = render "posts", { posts: posts }

= form_tag url_for(:only_path => false), method: :get, remote: true, id: "posts-form" do
 
  @tags.each do |tag|
    = check_box_tag "tags[]", tag[:id]
    = tag[:name]

  = submit_tag "Filter"

posts/show.js.erb:

$('#posts').html("<%= j (render 'posts', posts: @posts) %>")

mercredi 8 juillet 2020

Github actions rails commands "/bin/ruby: invalid option -: (-h will show valid options) (RuntimeError)"

Im trying to implement Github Actions but not able to run the rails commands.

Raises errors when running bundle exec rake or bundle exec rails db:create in the github workflow.

Run bundle exec rake rails db:setup
  bundle exec rake rails db:setup
  shell: /bin/bash -e {0}
  env:
    PATH: /home/runner/.rubies/ruby-2.6.5/bin:/usr/share/rust/.cargo/bin:/home/runner/.config/composer/vendor/bin:/home/runner/.dotnet/tools:/snap/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/linuxbrew/.linuxbrew/bin:/home/linuxbrew/.linuxbrew/sbin
    RAILS_ENV: test
    POSTGRES_HOST: localhost
    POSTGRES_USER: postgres
    POSTGRES_PASSWORD: postgres
    POSTGRES_PORT: 5432
    RUBYOPT: -W:no-deprecated -W:no-experimental
/home/runner/.rubies/ruby-2.6.5/bin/ruby: invalid option -:  (-h will show valid options) (RuntimeError)
##[error]Process completed with exit code 1.

and here is my ruby.yml file:

name: Ruby

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:
  test:

    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:11
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
        ports:
          - "5432:5432"
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5

    steps:
    - uses: actions/checkout@v2
    - name: Set up Ruby
      uses: ruby/setup-ruby@v1
      with:
        ruby-version: 2.6.5
    - name: Install library for postgres
      run: sudo apt-get install libpq-dev
    - name: Install dependencies
      run: bundle install
    - name: Setup Database
      run: bundle exec rake rails db:setup
      env:
        RAILS_ENV: test
        POSTGRES_HOST: localhost
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: postgres
        POSTGRES_PORT: 5432
        RUBYOPT: "-W:no-deprecated -W:no-experimental"
    - name: Run tests
      env:
        RAILS_ENV: test
        POSTGRES_HOST: localhost
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: postgres
        POSTGRES_PORT: 5432
        RUBYOPT: "-W:no-deprecated -W:no-experimental"
      run: bundle exec rake
    - name: Ensure that assets compile correctly
      run: bundle exec rails assets:precompile

Thank you everyone!

Ruby on Rails: How to write 'form.select' in _form.html.erb to show ONLY the categories that the user has created

I have a marketplace application where users can create both products and categories. In the product's _form.html.erb

In the product _form.html.erb a user can create a product and assign it one category. The issue is that the category 'form.select' displays all categories that all users have created.

How can I rewrite

  <div>
    <%= form.select :category_id, Category.all.map {|c| [c.category, c.id]} %>
  </div>

to display the categories only the current user has created?

--

<%= form_with(model: product, local: true) do |form| %>
  <% if product.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(product.errors.count, "error") %> prohibited this product from being saved:</h2>

      <ul>
        <% product.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>

  <div class="field">
    <%= form.label :description %>
    <%= form.text_area :description %>
  </div>

  <div class="field">
    <%= form.label :price %>
    <%= form.text_field :price %>
  </div>

  <div>
    <%= form.select :category_id, Category.all.map {|c| [c.category, c.id]} %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

but it lists all the categories in the database. How do I write this code so the form lists only the categories the user has produced.

database

  create_table "categories", force: :cascade do |t|
    t.string "category"
    t.bigint "user_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["user_id"], name: "index_categories_on_user_id"   end

  create_table "products", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.decimal "price", precision: 8, scale: 2
    t.bigint "user_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.integer "category_id"
    t.index ["user_id"], name: "index_products_on_user_id"   end

  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.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string "current_sign_in_ip"
    t.string "last_sign_in_ip"
    t.string "username"
    t.string "name"
    t.boolean "admin", default: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "uid"
    t.string "provider"
    t.string "access_code"
    t.string "publishable_key"
    t.string "stripe_id"
    t.boolean "subscribed"
    t.string "card_last4"
    t.string "card_exp_month"
    t.string "card_exp_year"
    t.string "card_type"
    t.text "perk_subscriptions", default: [], array: true
    t.string "s_name"
    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

mardi 7 juillet 2020

*1539 768 worker_connections are not enough while connecting to upstream

Deployed ruby backend api project to digitalocean server, i'm having issues configuring nagix and passenger when I make this api call "https://ift.tt/3ffOMmE" using postman i get this error based on cat /var/log/nginx/error.log

2020/07/08 02:59:11 [alert] 2769#2769: *1539 768 worker_connections are not enough while 
connecting to upstream, client: 159.65.65.203, server: borroup.com, request: "GET 
/api/v1/items HTTP/1.0", upstream: "http://159.65.65.203:80/api/v1/items", host: 
"159.65.65.203"

when i visit http://159.65.65.203/ i get this error

404 Not Found 
nginx/1.18.0

using Ubuntu 16.04.6 (LTS) x64 ruby 2.4.1

here is sudo nano /etc/nginx/sites-available/default

upstream app {
     server 159.65.65.203:80 fail_timeout=0;
}
# Default server configuration
server {
listen 80;
server_name borroup.com;
allow 159.65.65.203;
# this is where my react-app is located
root /var/www/development/ram/public/;
index index.html index.htm;

# Serve the static content (React app)
location / {
     try_files $uri /index.html =404;
 }

location /api {
     # Insert your public app path
     root /your/rails-app/path/public;
     proxy_pass http://app;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header Host $http_host;
     proxy_redirect off;
 }

 error_page 500 502 503 504 /500.html;
 client_max_body_size 4G;
 keepalive_timeout 10;
 }

here is sudo nano /etc/nginx/nginx.conf

 user deploy;
 worker_processes auto;
 pid /run/nginx.pid;

 events {
    worker_connections 768;
 }

 http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;
    access_log /var/log/nginx/access.log;
    gzip on;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

here is netstat -plunta

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program 
name
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      2769/nginx: 
worker
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      -
tcp        0      0 127.0.0.1:5432          0.0.0.0:*               LISTEN      -
tcp        0    976 159.65.65.203:22        222.186.30.167:11710    ESTABLISHED -
tcp        0      0 159.65.65.203:22        70.176.141.88:54472     ESTABLISHED -
tcp        0    604 159.65.65.203:22        184.101.50.220:55467    ESTABLISHED -
tcp6       0      0 :::22                   :::*                    LISTEN      -
udp        0      0 127.0.0.1:37075         127.0.0.1:37075         ESTABLISHED -

every time i change port i get similar but different wording errors

Note: This is a backend project does not have front end just used for api's

samedi 4 juillet 2020

how to send row id to another table while importing data from excel file in rails applicaiton

stage table has one_to_many association with task table. task table has attribute stage_id.
In my excel file there is parent child ID column like 1,2,3,4 is stage and 1.1,1.2..4.1..so on is task.

i want to import that file but the problem is how i'll take stage_id of new created row and put them is task table. so that while retrieving data no problem is faced.

if there is alternate easy solution to solve such problem please provide that solution. I have to save that in order, so that i can identify which has child and which is parent also there order.

stage.rb

  def self.import(file)
    accessible_attributes = ['stage','planned_start_date', 'planned_end_date', 'actual_start_date', 'actual_end_date']
    spreadsheet = Roo::Spreadsheet.open(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      stage =Stage.find_by_id(row["id"]) || new
      stage.attributes = row.to_hash.slice(*accessible_attributes)
      stage.save!
    end
  end

  def open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Roo::CSV.new(file.path, csv_options: {encoding: "SJIS"})
    when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
    when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end

index.html.erb

<%= form_tag import_project_stages_path(@project), multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import", :class=>"button warning" %>
<%end %>

vendredi 3 juillet 2020

NameError in Category#index

This is my category controller 
class CategoryController < ApplicationController

  def index  
    @category = Category.all    
  end

  def new
    @category = Category.new
  end

  def create
    @category = Category.new(params[:category])
    @category.save
    redirect_to @category   
  end

  def show
    @category = Category.find(params[:id])
  end



  private
    def category_params
      params.require(:category).permit(:name)
    end

    def find_post
      @category = Category.find(params[:id])
    end

end
This is my index page where i want to show all my categories
<h1>ALL CATEGORIES</h1>
<% @category.each do |c|%>
  <ul><%= link_to c.name, categories_path(category) %></ul> 
<% end %>
<%= link_to "Add Category", new_category_path %>  

These are the routes i have set for this controller

Rails.application.routes.draw do

root 'category#index'
post '/category' => 'category#create'
get '/category/new' => 'category#new', as:'new_category'
get '/category/:id' => 'category#show', as:'categories'

end Why i am getting this name error? undefined local variable or method category' for enter code here`#<#Class:0x00007feddc03ad50:0x00007fede47f8378> Did you mean? @category

mercredi 1 juillet 2020

Using checkboxes to pass multiple strings to array in migration with ruby

Im looking to have a user create a post where they specify what instruments they play. There should be a checkbox for each instrument so the user can select the ones that apply to the post. I was able to display the instruments and their checkboxes in the post creation but I cannot figure out how to save them to the post. I get error ActiveRecord::AssociationTypeMismatch.

Displaying all instruments and passing integers for each (Id like to pass strings)

  <% Instrument.all.each do |instrument| %>
    <%= check_box_tag "post[instruments][]", instrument.id %>
    <%= instrument.name %> <br>
  <% end %>

  <div class="actions">
    <%= form.submit %>
  </div> 

Migration to receive array of integers

class AddTagsToPost < ActiveRecord::Migration[5.2]
  def change
    add_column :posts, :instruments, :integer, array: true, :default => []
  end
end

schema.rb

 create_table "instruments", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.bigint "category_id"
    t.string "title"
    t.text "content"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "account_id"
    t.integer "instruments", default: [], array: true
    t.index ["account_id"], name: "index_posts_on_account_id"
    t.index ["category_id"], name: "index_posts_on_category_id"
  end

post.rb model

class Post < ApplicationRecord
  belongs_to :category
  belongs_to :account
  has_many :instruments
  validates :title, presence: true, length: { minimum: 3 }
  validates :content, presence: true, length: { maximum: 500 }

end

instrument.rb model

class Instrument < ApplicationRecord
  belongs_to :posts, optional: true
end