Wouter van den Beld

Joined

1,010 Experience
4 Lessons Completed
0 Questions Solved

Activity

Posted in Use datatables like handsontable

Hi,

I would love to see a episode that explains the use of json/ajax and load and save back data back to the server. For example i want to use handsontable (http://handsontable.com/) but i cant load (and save) data to it.

Posted in Subtract until zero then go to next record

HI,

i am running into a problem with the solution i implemented. this only works when dealing with whole numbers.

I have a WarehouseStock model and when i take items from stock it will set it to used and set the ledger where it was used for.

Now when we have item where the unit is in meters and we receive 6.5 meters how can i take a half item when i store each item individually.

Posted in Subtract until zero then go to next record

Thanks for thinking along Chris!

I will store each item individually, i thought this was wrong because when i get 200 screws it makes 200 records, I can however group by PurchaseOrder number and sum the total of the product to keep the views clear.

Also when i store each item individually it is easy to do a return booking i can find the the items and do set used to false and update the cost center to warehouse stock and it is returned.

Posted in Subtract until zero then go to next record

Hi,

I am looking for this:

for a warehouse application for ordering and keeping stock for machine maintenance .

i have multiple record of items that coming in.
On Monday i received a item 5 times for 1€ and on Wednesday i receive the same item for 1.50€ 3 times.

So now i have multiple lines of a product received.

now the mechanic takes out 6 of the item and i want to add budget cost of 6.50 to a machine. this is based on the first in first out principle.

so how can i rotate to the lines that still have items in it and subtract that to zero and go to next line.

I did write down something like this but it looks awful, is this something that could work or do i need a different approach.


def find_item(item, took_from_stock)
item = #find the linetems which has stock sorted on date
set_stock(item, took_from_stock)
end

def set_stock(item, took_from_stock)
  item = item
  x = took_from_stock

  x.times do
    item.stock - 1 
    x - 1
    unless 
      item.stock == 0
    else 
      find_next_item(item, x)
    end
  end
end

def find_next_item(item , x)
  if  x == 0
    item_complete
  else
item = #find the linetems which has stock sorted on date
set_stock(item, took_from_stock)
end
end

def item_complete
  # do some  stuff
end

Posted in AASM state based on variable

Hi Chris,

first of all, thank you for this great site! i love the videos and they are really helping me forward.

about my question, it looks kind of ugly but it works so i will leave it like this.

i found a solution for my naming problem.

instead of aasm_state you can call aasm.human_state and the text will be without the _
you can also use the .yml files to change the entire name i did not get that to work yet :)

Posted in AASM state based on variable

Hi,

I am using AASM and i want to set the state based on the total_price of a purchase order.
is this code below the way to go or can it be refactored.

before_save :check_budget


event :over_budget do
        transitions from: [:new, :new_approval_needed], to: :new_approval_needed
    end

    event :on_budget do
        transitions from: [:new, :new_approval_needed], to: :new 
    end

  end

    def check_budget
        if aasm_state = 'new' || 'new_approval_needed'
                  if total_price > 500
                  over_budget
                  else
                  on_budget
                end
            else
        end
    end

Also, is it possible to set custom state names without the _ because it looks ugly on the PO if the state is NEW_APPROVAL_NEEDED i would like it to be NEW APPROVAL NEEDED

Posted in ¿How make I to upload multiple images with refile?

And use the master branch or you will get undefined methods errors. (this step is not included in the readme)

gem 'refile', require: "refile/rails", git: 'https://github.com/refile/refile.git', branch: 'master'

Hi,

If you want to tackle the problem Andrew described: You don’t want someone manually typing http://yourapp.com/client/3 into their browser.

you can do the following using Pundit and using a association model:

class User < ActiveRecord::Base
  has_many :associations
  has_many :clients, through: :associations
end

class Association < ActiveRecord::Base
    belongs_to :user
    belongs_to :client
end

class Item < ActiveRecord::Base
  has_many :associations
  has_many :users, through: :associations
end

and your client_policy.rb will look like this:

class ClientPolicy < ApplicationPolicy

    def initialize(user, client)
    @user = user
    @client = client
  end

  class Scope < Scope
    def resolve
     if user.admin?
        scope.all
      else
        scope.where(:id => user.associations.pluck(:client_id))
      end
    end
  end

    def index?
        user.present?
    end

    def show?
   user.present? && @user.associations.pluck(:client_id).include?(@client.id)
    end

  def create?
    user.present? && user.admin?
  end

  def new?
    create?
  end

  def update?
    user.present? && @user.associations.pluck(:client_id).include?(@client.id)
  end

  def edit?
    update?
  end

  def destroy?
    user.present? && user.admin?
  end

end

This way you will only be allowed to clients where you have access to.

Posted in Handle money in Rails

Hi,

What do you think is the best way to handle money in rails?
At the moment i use a decimal field with a precision if 16 and a scale of 2.

the problem is that we use the comma as a decimal sign and this sometimes becomes a problem.

should i use the money gem or use only cents or do you guys have a better way to handle this?

when you set the config.time_zone the time will be saved as UTC.

When i set config.time_zone = 'Europe/Amsterdam' the SQL sets the time in UTC

  SQL (0.3ms)  UPDATE "assignments" SET "send_on" = $1, "status" = $2, "token" = $3, "updated_at" = $4 WHERE "assignments"."id" = 18  [["send_on", "2015-05-07 07:49:36.908033"], ["status", "send"], ["token", "72BKmqs-aYVC56wLTmM4lgiajqrsb7YvMHDzeM-zN9lw"], ["updated_at", "2015-05-07 07:49:36.908870"]]

When i call ruby <%= @assignment.send_on %> in the view i get 2015-05-07 09:49:36 +0200

When i set config.time_zone = 'Eastern Time (US & Canada)' restart the server i get 2015-05-07 03:49:36 -0400

Hi Chris,

Thank you! that did the trick!

when i was looking for a answer why to use Time.zone.now instead of DateTime.now i found an explanation on the following site:
http://winstonyw.com/2014/03/03/time_now_vs_time_zone_now/

is it a correct assumption that all times are stored in UTC format in the database and when you call the time from the database the time is set based on the timezone set in the application.rb?

Hi,

I have a strange problem
When i do the following method with no config.time_zone set in the application.rb it works.

def send_assignment
    @assignment = Assignment.find(params[:id])
    @assignment.update_attributes( :status => "send", :send_on => DateTime.now )

    AssignmentMailer.send_assignment(@assignment).deliver
    redirect_to @assignment, notice: Send'
  end

When i set the config.time_zone to

config.time_zone = 'Amsterdam'

i get the following error when i call the method

SystemStackError - stack level too deep:
  actionpack (4.1.5) lib/action_dispatch/middleware/reloader.rb:79:in `' 

If i remove the ruby :send_on => DateTime.now from the method i works.
So the DateTime.now causes a stack error when i set the config.time_zone.

Suggestions?

Posted in Render \r\n in javascript.erb

I actually needed the \r\n because when you add .val with jquery on a text field it uses that to put the new lines in the right place.

so when you use simple_format you get the <br/> as text in your field.
Your answer was still great because

$("#assignment_conditions").val("<%=j @company.conditions %>");

did the trick!

Posted in Render \r\n in javascript.erb

HI,

I try to add the value of a text field in a form from a other database field.
I use the following javascript

$("#assignment_conditions").empty();
$("#assignment_conditions").val("<%= @company.conditions%>");

this however fills in

$("#assignment_conditions").empty();
$("#assignment_conditions").val("Op deze opdracht zijn de volgende voorwaarden en condities van toepassing in volgorde van
belangrijkheid:

----

De hierboven vermelde documenten zijn in het verleden eerder verstrekt aan opdrachtnemer en
vormen de basis voor het komen tot een service- en onderhoudsovereenkomst tussen opdrachtgever en
opdrachtnemer");

i need this

$("#assignment_conditions").empty();
$("#assignment_conditions").val("Op deze opdracht zijn de volgende voorwaarden en condities van toepassing in volgorde van\r\nbelangrijkheid:\r\n\r\n----\r\n\r\nDe hierboven vermelde documenten zijn in het verleden eerder verstrekt aan opdrachtnemer en\r\nvormen de basis voor het komen tot een service- en onderhoudsovereenkomst tussen opdrachtgever en\r\nopdrachtnemer.");

when i use @company.conditions.to_json it works because to output is like this

$("#assignment_conditions").empty();
$("#assignment_conditions").val(&quot;Op deze opdracht zijn de volgende voorwaarden en condities van toepassing in volgorde van\r\nbelangrijkheid:\r\n\r\n----\r\n\r\nDe hierboven vermelde documenten zijn in het verleden eerder verstrekt aan opdrachtnemer en\r\nvormen de basis voor het komen tot een service- en onderhoudsovereenkomst tussen opdrachtgever en\r\nopdrachtnemer&quot;);

This adds " so this is not ideally. i tried to_html and gsub but i don't get the right result. Any suggestions?

After a airpair session i got it to work.

We used a lot of methods because you can call them in the console when you use the byebug gem.

but we did it the way you suggested!


class DetailAction < ActiveRecord::Base
    belongs_to :item_detail
    has_many :detail_action_amounts ,dependent: :destroy
    has_many :budget_items ,dependent: :destroy
    accepts_nested_attributes_for :detail_action_amounts, :reject_if => :all_blank, :allow_destroy => true

    before_create :set_default, on: :create
    before_save :set_sum
    after_save :recalculate_overridden_actions

    def set_default
        item_detail = ItemDetail.where(:id => self.item_detail_id)
        item = Item.where(:id => item_detail[0].item_id)

        self.starting_year = item[0].construction_date + self.condition_three
        self.amount = '1' unless self.amount
        self.cycle = self.condition_three
    end


    def set_sum
        if self.cycle?
            self.sum = self.amount * self.norm
            self.sequence = calculate_sequence  
        else
            self.sum = self.amount * self.norm  
        end
    end

    def recalculate_overridden_actions
        overridden_actions.each(&:set_sum).each(&:save)
    end

    def calculate_sequence
        basic_sequence - overriding_sequences.flatten
    end

    def basic_sequence
        starting_year.step(starting_year + 500, step = cycle ).to_a
    end

    def overriding_sequences
        overriding_actions.map(&:basic_sequence)
    end

    def overriding_actions
        item_detail.detail_actions.to_a.select do |action|
            self.is_overridden_by?(action)
        end
    end

    def overridden_actions
        item_detail.detail_actions.to_a.select do |action|
            action.is_overridden_by?(self)
        end     
    end

    def is_overridden_by?(other_action)
        other_action.hierarchy < hierarchy &&
            other_action.hierarchy.first == hierarchy.first 
    end

end

I'm working on a maintenance planning/cost application. With the help of gorails, onemonth, codeschool and all other great resources I am almost ready to launch the first release. However I can really use some help for the last part.

I have a items model where I store the item information. An item can be a building, factory, swimming pool or even a single machine or room. A item has many ItemDetails and a ItemDetail has many DetailActions.

For Example:

We have a Item :
Building A

Item “Building A” has a ItemDetail:
electric water heater 80 liter:

ItemDetail “electric water heater 80 liter” has the following DetailActions:
electric water heater (replace)
electric water heater (maintenance)
heat distributor (replace)
heat distributor (maintenance)

The DetailActions model looks like this:

id :integer not null, primary key
name :text
unit :string(255)
starting_year :integer
hierarchy :string(255)
norm :decimal(14, 2)
condition_one :integer
condition_two :integer
condition_three :integer
condition_four :integer
condition_five :integer
item_detail_id :integer
created_at :datetime
updated_at :datetime
amount :decimal(16, 2)
sum :decimal(16, 2)
cycle :integer
sequence :string(255) default([]), is an Array

when an item is created the model calculates the sum and it sets the sequence and that's where I need some help.

Currently the sequence is set like this in the detailaction model:

self.sequence = self.starting_year.step(self.starting_year + 500, step = self.cycle ).to_a

this gives something like the following:

["2026", "2036", "2046", "2056", "2066", "2076", "2086", "2096", "2106", "2116", "2126", "2136", "2146", "2156", "2166", "2176", "2186", "2196", "2206", "2216", "2226", "2236", "2246", "2256", "2266", "2276", "2286", "2296", "2306", "2316", "2326", "2336", "2346", "2356", "2366", "2376", "2386", "2396", "2406", "2416", "2426", "2436", "2446", "2456", "2466", "2476", "2486", "2496", "2506", "2516", "2526"]

as you can imagine you wont need to do any maintaince to the heat distributor when we replace the heat distributor that year. So thats where the hierarchy comes in. in the example the hierarchy would be like this:

electric water heater (replace) 101
electric water heater (maintenance) 102
heat distributor (replace) 201
heat distributor (maintenance) 202

so when the electric water heater gets replaced in for example 2036 we would not like to do any maintenance.

I would like to achieve this to set the sequence based on the hierarchy.

In the console I can do (for example) take the id's the heat distributor

replace = DetailAction.find(5598)
maintenance = DetailAction.find(5599)

replace.sequence
=> ["2036", "2061", "2086", "2111", "2136", "2161", "2186", "2211", "2236", "2261", "2286", "2311", "2336", "2361", "2386", "2411", "2436", "2461", "2486", "2511", "2536"]

maintenance.sequence
=> ["2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030", "2031", "2032", "2033", "2034", "2035", "2036", "2037", "2038", "2039", "2040", "2041", "2042", "2043", "2044", "2045", "2046", "2047", "2048", "2049", "2050", "2051", "2052", "2053", "2054", "2055", "2056", "2057", "2058", "2059", "2060", "2061", "2062", "2063", …...............................]

and simple do new_maintenance_sequence
= maintenance.sequence

  • replace.sequence

new_maintenance_sequence = maintenance.sequence - replace.sequence
=> ["2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030", "2031", "2032", "2033", "2034", "2035", "2037", "2038", "2039", "2040", "2041", "2042", "2043", "2044", "2045", "2046", "2047", "2048", "2049", "2050", "2051", "2052", "2053", "2054", "2055", "2056", "2057", "2058", "2059", "2060", "2062", "2063", "….............................]

I am stuck how to implement this in the model. I would like to loop trough all the DetailActions that belong to the ItemDetail to set the sequence

so when the hierarchy is:

a = 101
b = 102
c = 103
d = 201
e = 202

the sequence get set like:

c = c – b + a
b = b = b- a
a = a
e = e – d
d = d

Do you guys can get me on the right track or is the path i chose wrong?

My current detail action model looks like this:


class DetailAction < ActiveRecord::Base
 belongs_to :item_detail
 has_many :detail_action_amounts ,dependent: :destroy
 has_many :budget_items ,dependent: :destroy
 accepts_nested_attributes_for :detail_action_amounts, :reject_if => :all_blank, :allow_destroy => true

 before_create :set_default
 before_save :set_sum

def set_default
    item_detail = ItemDetail.where(:id => self.item_detail_id)
    item = Item.where(:id => item_detail[0].item_id)

    self.starting_year = item[0].construction_date + self.condition_three
    self.amount = '1' unless self.amount
    self.cycle = self.condition_three
    self.sum = self.amount * self.norm

    self.sequence = self.starting_year.step(self.starting_year + 500, step = self.cycle ).to_a

end


def set_sum
    if self.cycle?
        self.sum = self.amount * self.norm
        self.cycle = self.condition_three unless self.cycle
        self.sequence = self.starting_year.step(self.starting_year + 500, step = self.cycle ).to_a
    else
        self.sum = self.amount * self.norm  
    end
end

end

Posted in field_for with index

I have a form that uses java script and the data-attribute to do some calculations (Calx2).
to make the data-attributes unique i use the the index method that is available.

<tbody id="detail_list">
      <%= f.fields_for :detail_action_amounts, remote:true, :wrapper => false do |detail_action_amount| %>
        <tr class="fields">
           <td><%= detail_action_amount.text_field :description %></td>
           <td><%= detail_action_amount.text_field :amount :data => { :cell=> "A#{detail_action_amount.index}"} %></td>
           <td><%= detail_action_amount.text_field :factor :data => { :cell=> "B#{detail_action_amount.index}"} %></td>
           <td><%= detail_action_amount.text_field :length :data => { :cell=> "C#{detail_action_amount.index}"} %></td>
           <td><%= detail_action_amount.text_field :width, :data => { :cell=> "D#{detail_action_amount.index}"} %></td>
           <td><%= detail_action_amount.text_field :height :data => { :cell=> "E#{detail_action_amount.index}"} %></td>
           <td><%= detail_action_amount.text_field :total  :data => { :cell=> "F#{detail_action_amount.index}", :formula=> "A#{detail_action_amount.index}*(C#{detail_action_amount.index}*D#{detail_action_amount.index}*E#{detail_action_amount.index})/100*B#{detail_action_amount.index}"} %></td>
          <td><%= detail_action_amount.link_to_remove "Verwijder", :class => "btn btn-outline btn-red btn-smal btn-remove" %></td>
        </tr>
      <% end %>
    </tbody>
     <tfoot>
            <tr>
                <td colspan="6">Totaal</td>
                <td><%= f.text_field :amount, class: 'labelsize50', :data => { :cell=> "G1", :formula=> "SUM(F0:F1000)"} %></td>
                <td colspan="2"></td>
            </tr>
        </tfoot>
    </table>

This all works but when i add a field the index method adds the time in milliseconds instead of a ascending number.
is there a good and simple way to use a ascending number?

Posted in Capistrano deployment errors

Hi,

Thanks Chris! i got it working again. i checked my capfile and i forget to add

require 'capistrano/rbenv'

after i added this to my capfile i was getting

DEBUG[7cacbd08] Running /usr/bin/env [ ! -d /usr/local/rbenv/versions/2.1.5p273 ] on 
DEBUG[7cacbd08] Command: [ ! -d /usr/local/rbenv/versions/2.1.5p273 ]
DEBUG[7cacbd08] Finished in 0.587 seconds with exit status 0 (successful).
ERRORrbenv: 2.1.5p273 is not installed or not found in /usr/local/rbenv/versions/2.1.5p273
cap aborted!

So i looked in ~/.rbenv/versions$ and noticed the folder was named 2.1.5. so edited my capfile again from:

:rbenv_ruby, '2.1.5p273'

to

:rbenv_ruby, '2.1.5'

run deploy again and it all works now.

still have to run db:migrations and bundle manually so that is my next challange.

Posted in Capistrano deployment errors

Yes, i did have the same versions locally and on my server i installed 2.1.5 now on both machines and i still get the same error.
I tried to install the gem on my production server in the current folder and the gem will install.

even if i go to my releasees folder and go to the latest uploaded release and run bundle the working gem will be installed.

Installing working_hours 1.0.2
Your bundle is complete!
Gems in the groups development and test were not installed.
It was installed into /home/deploy/btapp/shared/bundle
[email protected]:~/btapp/releases/20141210085038$

Posted in Capistrano deployment errors

Hi,

I installed the working_hours gem to calculate SLA hours on my ticketsystem. It all works on dev so i was ready to deploy it to the production machine with capistrano

now i get the following errors when i run cap deploy:

DEBUG[be1a04f1] rake aborted!
DEBUG[be1a04f1] SyntaxError: /home/deploy/btapp/shared/bundle/ruby/1.9.1/gems/working_hours-1.0.2/lib/working_hours/computation.rb:7: syntax error, unexpected tLABEL
DEBUG[be1a04f1] def add_days origin, days, config: nil
DEBUG[be1a04f1] ^
DEBUG[be1a04f1] /home/deploy/btapp/shared/bundle/ruby/1.9.1/gems/working_hours-1.0.2/lib/working_hours/computation.rb:21: syntax error, unexpected tLABEL
DEBUG[be1a04f1] def add_hours origin, hours, config: nil
DEBUG[be1a04f1] ^
DEBUG[be1a04f1] /home/deploy/btapp/shared/bundle/ruby/1.9.1/gems/working_hours-1.0.2/lib/working_hours/computation.rb:26: syntax error, unexpected tLABEL
DEBUG[be1a04f1] def add_minutes origin, minutes, config: nil

i am on ruby 2.1.2 and when i run rbenv versions i dont see 1.9.1 is that normal?
i tried different gem version of working_hours but i still get the same errors,
Any ideas?

logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.