I need to set a condition where, if my_counter is equal to 0, 1 or 2, then my validation flag is set to true, otherwise set my validation flag to false.
But my validate_inclusion_of call isn't working:
if User.find_by_email(#email)
user = User.find_by_email(#email)
user.my_count += 1
user.save
# Here is where it fails
if validates_inclusion_of :my_count, :in => [0,1,2]
#my_flag = true
else
#my_flag = false
end
That is not how you setup validations on models. May I suggest you do this:
#my_flag = [0,1,2].include? user.my_count
Edit: let me point out that you are finding your User twice which results in 2 queries. Consider doing this:
if user = User.find_by_email(#email)
user.my_count += 1
user.save
#my_flag = [0,1,2].include? user.my_count
end
Related
Using Rails 6 and Ruby 2.7
I run calculations using callbacks, which works on create; however, this does not work on update. Unless marked complete, my calculation gets stuck in a loop. So, in order to edit/update I'm attempting to use the before_update to mark complete as false, and then run the same calculation as create and then marking it back to true. I can get it to break the loop and update the attributes, however, it does not run the calculations like it does upon create.
I've been trying so many variations to get this to work and feel absolutely lost. I've tried various callbacks and have gone through documentation and have been searching for an answer. If anyone can give me a clue, hint, or any insight, please. I am not receiving any errors of any kind.
For the .previous method, I am using the By_star gem and for the .second_to_last method, I am using the groupdate gem.
Thank you for your time.
belongs_to :user
belongs_to :store
after_create :create_calculations
before_update :before_update_calculations
after_update :update_calculations
def create_calculations
store = Store.find(self.store_id)
sheet = Sheet.find(self.id)
past_sheet = store.sheets.second_to_last
unless store.sheets.last
s = past_sheet.draw - sheet.returned
else
s = sheet.sold
end
unless past_sheet
s = store.sheets.last.draw - sheet.returned
else
s = past_sheet.draw - sheet.returned
end
if sheet.complete != true && sheet.store.vending_box == true
sheet.update(complete: true)
sheet.update(sold: s)
short = (sheet.sold * 0.75) - sheet.collected
sheet.update(:shortage => short)
pilferage = (sheet.shortage / 0.75)
sheet.update(:pilferage => pilferage)
elsif sheet.complete != true && sheet.store.vending_box == false
sheet.update(complete: true)
sheet.update(sold: s)
short = (sheet.sold * 0.55) - sheet.collected
sheet.update(:shortage => short)
pilferage = (sheet.shortage / 0.55)
sheet.update(:pilferage => pilferage)
else
end
end
def before_update_calculations
unless Sheet.find(self.id).complete == true
Sheet.find(self.id).update(complete: false)
end
end
def update_calculations
store = Store.find(self.store_id)
sheet = Sheet.find(self.id)
past_sheet = store.sheets.find(self.id).previous
# will add back conditionals to deal with the .previous method, for when
# it's the first record and as no previous item, such as in the create.
s = past_sheet.draw - sheet.returned
if sheet.complete != true && sheet.store.vending_box == true
sheet.update(complete: true)
sheet.update(:sold => s)
short = (sheet.sold * 0.75) - sheet.collected
sheet.update(:shortage => short)
pilferage = (sheet.shortage / 0.75)
sheet.update(:pilferage => pilferage)
elsif sheet.complete != true && sheet.store.vending_box == false
sheet.update(complete: true)
sheet.update(:sold => s)
short = (sheet.sold * 0.55) - sheet.collected
sheet.update(:shortage => short)
pilferage = (sheet.shortage / 0.55)
sheet.update(:pilferage => pilferage)
else
end
end
end```
You call update in your after_update which starts a new cycle of update callbacks.
I'd rather use methods which I call explicitly over callbacks but if you want to stick to callbacks, try assigning values in a before_update callback the data will be updated once.
A good way to avoid infinite update loops on callbacks, is to use a variable that is only used to that purpose. This variable should work as a flag. When up, run the callback. Otherwise, just skip it.
Thus, you could do, for your example, do the following:
attr_accessor :this_is_the_flag
after_update update_calculations, :if => "this_is_the_flag.nil?"
def update_calculations
[...]
self.this_is_the_flag = true # invalidate the callback
end
This is the general idea, you can adjust this to your need. Also, please, make sure the syntax is correct, because callback syntax tends to change regularly.
I create a class that takes two input parameters from the user, these input parameters are then used to create five others, the problem is that the five others don't show up when I check my validated paramaters only the first ones.
I know that all of the new parameters are added to the params but they don't show up in the model time_delta_params hash when I check what's in it only the first two. Thanks for any help!
My create method for the controller
def create
# XXX Add these columns to the model and populate them
# finalRating, positiveTweets, negativeTweets, neutralTweets, totalTweets
tweetRatings = {:finalRating => 0, :positiveTweets => 0, :negativeTweets => 0, :neutralTweets => 0}
#stock = Stock.find(params[:stock_id])
tweets = getTweets(#stock.hashtag, time_delta_params[:start], time_delta_params[:length].to_i)
tweets.each do |tweet|
case processTweet(tweet)
when 1
tweetRatings[:positiveTweets] += 1
tweetRatings[:finalRating] += 1
when -1
tweetRatings[:negativeTweets] += 1
tweetRatings[:finalRating] -= 1
else
tweetRatings[:neutralTweets] += 1
end
end
params[:final] = tweetRatings[:finalRating]
params[:positive] = tweetRatings[:positiveTweets]
params[:negative] = tweetRatings[:negativeTweets]
params[:neutral] = tweetRatings[:neutralTweets]
params[:total] = tweets.count
# printSomthingToRender(time_delta_params)
#time_delta = #stock.time_deltas.create(time_delta_params)
redirect_to stock_path(#stock)
end
My validation:
def time_delta_params
params.require(:time_delta).permit(
:start,
:length,
:final,
:positive,
:negative,
:neutral,
:total
)
end
You are not merging the additional parameters into the time_delta hash, but straight to the top level of params. time_delta is a hash within params.
You need to do something like:
params[:time_delta].merge!(final: tweetRatings[:finalRating],
positive: tweetRatings[:positiveTweets],
negative: tweetRatings[:negativeTweets],
neutral: tweetRatings[:neutralTweets],
total: tweets.count)
You're calling create with the time_delta_params that isn't going to contain the tweetRatings data. You would need to do something like params['time_delta'][:final] = tweetRating[:finalRating]. You could also call create and create your hash there or rename the values in the tweetRatings hash to match what is in the model.
I have Coupon model and in this model file I have a suitable_for_use method.I want to list Coupons if coupon.suitable_for_use == true.Is there any short way to do this ? I wrote this code but it doesn't work.
#coupons = []
coupons = Coupon.all.each do |coupon|
if coupon.suitable_for_use
#coupons << coupon
end
end
#coupons = coupons
suitable_for_use method
def suitable_for_use
result = true
if is_used?
result = false
elsif self.start > Time.now.in_time_zone
result = false
elsif self.end < Time.now.in_time_zone
result = false
end
return result
end
The problem is your assigning twice to #coupons. The return value from each is the collection it was given. So your last line reassigns the original set of coupons returned by Coupon.all.
#coupons = Coupon.all.select(&:suitable_for_use)
If your not sure what that does, here's the expanded version.
#coupons = Coupon.all.select {|coupon| coupon.suitable_for_select}
Basically, select takes a block that it will iterate over and if the block returns true then it will add that element to the returned collection. So any coupon that returns false will not be returned by select.
The &:suitable_for_use is called a symbol to proc. It literally expands to the block in the second line and is pretty common in ruby one-liners.
I'm making an task-manager and have an boolean attribute for 'finished'. I've tried to override the setter to implement an 'finished_at' date when i toggle 'finished' to true.
But i getting some mixed result. It doesn't work in browser but it will work in my rspec test.
Please help me out.
class TasksController < ApplicationController
# ...
def update
# ..
if #task.update_attributes(params[:task]) # where params[:task][:finished] is true
# ...
end
class Task < ActiveRecord::Base
#...
def finished=(f)
write_attribute :finished, f
write_attribute :finished_at, f == true ? DateTime.now : nil
end
end
# and in rspec i have
describe "when marked as finished" do
before { #task.update_attributes(finished: true) }
its(:finished_at) { should_not be_nil }
its(:finished_at) { should > (DateTime.now - 1.minute) }
describe "and then marked as unfinished" do
before { #task.update_attributes(finished: false) }
its(:finished_at) { should be_nil }
end
end
in browser it executes "UPDATE "tasks" SET "finished" = 't', "updated_at" = '2012-10-02 18:55:07.220361' WHERE "tasks"."id" = 17"
and in rails console i got the same with update_attributes.
But in rspec with update_attributes i get "UPDATE "tasks" SET "finished" = 't', "finished_at" = '2012-10-02 18:36:47.725813', "updated_at" = '2012-10-02 18:36:51.607143' WHERE "tasks"."id" = 1"
So I use the same method but it's only working in rspec for some reson...
using latest rails and latest spec (not any rc or beta).
Solution
Not mush i did need to edit. Thanks #Frederick Cheung for the hint.
I did notice i did like "self[:attr]" more than "write_attribute". Looks better imo.
def finished=(value)
self[:finished] = value
self[:finished_at] = (self.finished? ? Time.now.utc : nil)
end
Your setter is passed the values as they are passed to update_attributes. In particular when this is triggered by a form submission (and assuming you are using the regular rails form helpers) f will actually be "0" or "1", so the comparison with true will always be false.
The easiest thing would be to check the value of finished? after the first call to write_attribute, so that rails can convert the submitted value to true/false. It's also unrubyish to do == true - this will break if the thing you are testing returns a truthy value rather than actually true (for example =~ on strings returns an integer when there is a match)
You could use ActiveRecord Dirty Tracking to be notified of this change.
http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
class Task < ActiveRecord::Base
before_save :toggle_finished_at
def toggle_finished_at
if finished_changed?
before = changes['finished'][0]
after = changes['finished'][1]
# transition from finished => not-finished
if before == true && after == false
self.finished_at = nil
end
# transition from not finished => finished
if before == false && after == true
self.finished_at = Time.now.utc
end
end
end
end
This is a use case for a state machine. You call a :finish! event (a method) which is configured to change the state and to do whatever else needed.
https://github.com/pluginaweek/state_machine/
I'm trying to trigger a warning when a price is entered too low. But for some reason, it always returns true and I see the warning regardless. I'm sure there something wrong in the way I'm doing this as I'm really new to RoR.
In model:
def self.too_low(value)
res = Class.find_by_sql("SELECT price ……. WHERE value = '#{value}'")
res.each do |v|
if #{value} < v.price.round(2)
return true
else
return false
end
end
end
In controller:
#too_low = Class.too_low(params[:amount])
if #too_low == true
flash[:warning] = 'Price is too low.'
end
I would write it somewhat different. You iterate over all items, but you are only interested in the first element. You return from inside the iteration block, but for each element the block will be executed. In ruby 1.9.2 this gives an error.
Also i would propose using a different class-name (Class is used to define a class)
So my suggestion:
Class YourGoodClassName
def self.too_low(amount)
res = YourGoodClassName.find_by_sql(...)
if res.size > 0
res[0].price.round(2) < 1.00
else
true
end
end
end
You can see i test if any result is found, and if it is i just return the value of the test (which is true or false); and return true if no price was found.
In the controller you write something like
flash[:warning] = 'Price is too low' if YourGoodClassName.too_low(params[:amount])