Rails redirect_to not working - ruby-on-rails

I have a filter_before filter that checks to see if a param is true. If it is my app does this. However, the && return seems to be causing some problems. When I take it out, it'll redirect form every page to the desired countdown page--but then it loops or double renders.
redirect_to :countdown && return if #online == 1
Is there a way to wrap this in an if statement?
Something like:
if current_page(:countdown)
redirect_to :countdown if #online == 1
end

You'd better exclude the countdown action from your before_filter to avoid infinite loop.
something like:
before_filter :check_countdown, :except => :countdown
That said, what you did is valid:
redirect_to :countdown and return if #online == 1

You need to use and instead of &&.
From the Rails Guide:
Make sure you use and return and not && return because while the
former will work, the latter will not due to operator precedence in
the Ruby Language.
http://guides.rubyonrails.org/layouts_and_rendering.html

It might be work for you
return redirect_to :countdown if #online == 1

Related

How to not cache if certain condition is met on Rails 6.1 +Ruby

I want to make it so if its directReports it shouldn't get it from rails cache. I tried to just return it but that doesnt seem to work.
''' # dont get it from cache if DirectReports
when PerformanceManagement::V0::EmployeeFilter::DirectReports
return
else
filtered_results = loaded_records
end'''
plz don't be mean it's my first time posting.
For such things you can create a method that just acts as a wrapper to handle the cache-or-not condition:
def main_logic_here
... expensive calculation
end
def main_logic_wrapper
if true
main_logic_here
else
Rails.cache.fetch(...) { main_logic_here }
end
end

Bot spamming with invalid utf-8 characters

Our rails app is being slammed by a random spamming bot and they are trying to post some weird stuff.
I already tried different solutions:
The gem invalid_utf8_rejector
The gem rack-uri_sanitizer
Some custom code in our application_controller.rb file in a
before_filter method. before_filter :force_utf8_params
def force_utf8_params
traverse = lambda do |object, block|
if object.kind_of?(Hash)
object.each_value { |o| traverse.call(o, block) }
elsif object.kind_of?(Array)
object.each { |o| traverse.call(o, block) }
else
block.call(object)
end
object
end
force_encoding = lambda do |o|
return redirect_to #MYAPP_URL+"/not-found" if o.is_a?(String) && !o.valid_encoding?
end
traverse.call(params, force_encoding)
end
Here is the error we are getting: invalid byte sequence in UTF-8
I don't know what else to do.
you need to change your code a bit, the original solution for this problem uses lamda, which is appropriate, since it tries to force encode or strip some characters. But you need to redirect and proceed with execution, so you need to use proc.
force_encoding = proc do |o|
redirect_to #MYAPP_URL+"/not-found" and return if o.is_a?(String) && !o.valid_encoding?
end

Rails controllers: halt action execution after render

I have a Rails 4.0.2 controller action which is called by a method submission. Inside this method I check for a particular field to match a criteria and in case it is not matched, I want to present an error to the user and call render new again, without going any further within the method. So I wrote:
discount_coupon = DiscountCoupon.where(code: discount_code).first
if discount_coupon.nil? || (discount_coupon.present? && !discount_coupon.currently_active?)
flash[:alert] = t("flash.entries.create.invalid_coupon_code")
render :new
return
end
#entry.save
So, in my app when the discount_coupon variable is wrong and the program enters the conditional, it should halt its execution on return but somehow it does not and the #entry.save method is called and screws up the whole thing.
What am I doing wrong? I appreciate any help!
why don't you just enclose #entry.save with an else condition and remove return? so that if the discount coupon condition fails it renders the action :new else it just saves the entry.
As it's been suggested, try if/else conditional:
discount_coupon = DiscountCoupon.where(code: discount_code).first
if discount_coupon.nil? || (discount_coupon.present? && !discount_coupon.currently_active?)
flash[:alert] = t("flash.entries.create.invalid_coupon_code")
render :new
else
#entry.save
end
you can refactor this code once you are sure it is working.

Ruby "&&" causes internal server error on Rails ajax call and "and" doesn't. What's the difference between the two?

I'm building my first Rails app and I'm using JQuery to make an ajax POST request to update a resource. I'm sending _method: "PATCH" and the correct controller is being executed:
def update
#buddyship = Buddyship.find(params[:id])
if #buddyship.involve? current_user && #buddyship.update(buddyship_params)
render json: { success: true }
else
render json: { success: false }, :status => 500
end
end
I'm testing the standard use case first, where the relationship does involve the current user, so the first part of the condition evaluates to true. The second does too, I know it because I tried
def update
#buddyship = Buddyship.find(params[:id])
bool = #buddyship.update(buddyship_params)
logger.debug "bool: "+bool.to_s
if #buddyship.involve? current_user && bool
render json: { success: true }
else
render json: { success: false }, :status => 500
end
end
and in the logs I got bool: true. Plus, the record still gets updated in the database. Still somehow I get Internal Server Error instead of success.
If I simply use and instead of &&, everything works as I expected.
if #buddyship.involve? current_user && #buddyship.update(buddyship_params)
I understand that and has lower precedence than &&, and that the assignment operator = is in between. But in this context this doesn't seem to be relevant, after all there's only one operator! So it's not competing for precedence with anything else. It seems pretty straightforward. What am I getting wrong???
&& has strong precedence and and has low precedence.
#buddyship.involve? current_user && #buddyship.update(buddyship_params)
is the same as
#buddyship.involve?(current_user && #buddyship.update(buddyship_params))
and
#buddyship.involve? current_user and #buddyship.update(buddyship_params)
is the same as
#buddyship.involve?(current_user) and #buddyship.update(buddyship_params)
Use braces to wrap them as the spaces may break logic.
Change this
if #buddyship.involve? current_user && #buddyship.update(buddyship_params)
To
if (#buddyship.involve? current_user) && (#buddyship.update buddyship_params)

Rails 3 - Refactor ruby conditions

I'd like to know if there is a simpler way to do these 2 conditions in ruby :
if params[:action] == 'index' || params[:action] == 'show'
and
if !(comment = (session[:my_params].include?(:comment) rescue nil)).nil?
Thanks in advance
For the first one, you could do:
if %w(index show).include?(params[:action])
The second should really be re-factored into two lines: assignment within a condition check is a code smell; there's never a reason for it.
If you're using Rails / ActiveSupport, you can take advantage of Object#try
comment = session[:my_params].try(:include?, :comment)
if comment
# ... comment is in scope
end
Otherwise, you're left with something slightly clunkier:
comment = session[:my_params].include?(:comment) rescue nil
if comment
# etc
1:
if ['index','show'].include? params[:action]
2:
if (comment = (session[:my_params].include?(:comment) rescue nil))
! and .nil? in second condition are redundant
But, really, you should not try to make everything as short as possible, the first thing to care about is how clear your code would be for other people. The second condition should look like:
if ( comment = (session[:my_params] && session[:my_params].include?(:comment) )
or even
comment = session[:my_params] && session[:my_params].include?(:comment)
if comment
First one can be refractored like this:
if ['index', 'show'].include? params[:action]
or
if %w(index show).include? params[:action]
This should be faster than using an array and include?:
case params[:action]; when 'index', 'show'
...
end
The second one:
if comment = (session.fetch(:my_params, {}).include?(:comment))

Resources