简体   繁体   中英

is there a more elegant way to write this? variable within activerecord is not nil

I ruby on rails, in view, I would like to check if there is some variable not null. I suppose first I must check if there is even a object and then check if that r1!=nil. Is there a better way? thank you

      <% neki=Anketare.where("semestar_id=? AND JMBAG=? AND sifPred=? and vrstaNastave=?",session[:semestar_id],predmett.JMBAG,params[:format],Vrstanastave.find(1).vrstaNastave) %>
  <% if neki.exists? %>
    <% if neki.first.r1!=nil %>
        A+
    <% else %>
    A-
    <% end %>       
    <% else %>
    A-
    <% end %>       

Using the ternary operator , I would suggest something like

Model or controller! -

@neki=Anketare.where("semestar_id=? AND JMBAG=? AND sifPred=? and vrstaNastave=?",
session[:semestar_id],predmett.JMBAG,params[:format],
Vrstanastave.find(1).vrstaNastave)

View:

<%= @neki.exists? ? (@neki.first.r1!=nil ? "A+" : "A-") : "A-" %>  

might work.

You need the @ to share the variable between the controller and the view.

You can use foo.nil? to test if something is nil. So you can call neki.first.r1.nil? to test if it's nil. You can also just use the item itself as a boolean test:

if neki.first.r1; do_something; else; do_something_else; end

With rails you can also use foo.blank? to check if something is not nil and is not a blank string or empty array. Rails also gives you foo.present? to check if something is not blank? (the same as !foo.blank? )

So in your case you can simply change the entire set of if statements to:

<%= (neki.present? and neki.first.r1) ? "A+" : "A-" %>

Ugh. Use the andand gem :

<%= @neki.andand.first.r1 ? "A+" : "A-" %>

I wouldn't include any of the logic in the view. Instead, you can write a model that performs the logic on neki and neki.first.r1 and figures out the grade, then call that from your view.

Example:

# Model
class Neki
  def initialize(neki)
    @neki = neki
  end
  def grade
    (neki.present? and neki.first.r1) ? "A+" : "A-"
  end
end

# Controller
@neki = Neki.new(Anketare.where(...))

# View
<%= @neki.grade %>

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM