@users = User. find ( :all ) activated_users = 0 foreach user in @users activated_users + = 1 if user. activated == 1 end # , activated_users == @users . size
@users = User. find ( :all ) activated_users = 0 foreach user in @users activated_users + = 1 if user. activated == 1 end # , activated_users == @users . size
@users = User. find ( :all ) activated_users = 0 foreach user in @users activated_users + = 1 if user. activated == 1 end # , activated_users == @users . size
@users = User. find ( :all ) activated_users = 0 foreach user in @users activated_users + = 1 if user. activated == 1 end # , activated_users == @users . size
@users = User. find ( :all ) activated_users = 0 foreach user in @users activated_users + = 1 if user. activated == 1 end # , activated_users == @users . size
@users = User. find ( :all ) activated_users = 0 foreach user in @users activated_users + = 1 if user. activated == 1 end # , activated_users == @users . size
@users = User. find ( :all ) activated_users = 0 foreach user in @users activated_users + = 1 if user. activated == 1 end # , activated_users == @users . size
But even this record did not suit me afterwards. I found a more rational option:
- @users = User. find ( : all )
- activated_users = 0
- I personally like this way of recording more
- # than standard for many languages ​​foreach cycle
- @users . each do | user |
- activated_users + = 1 if user. activated == 1
- end
- # or in one line:
- @users . each { | user | activated_users + = 1 if user. activated == 1 }
However, all good things have already been invented for us, you just need to read the documentation. Arrays have a wonderful all method ?, which checks whether all elements satisfy the condition. By the way, there is still the any? Method that returns true if at least one element meets the condition.
- # The select method allows you to pull out the elements of the array for a given condition
- # And then we compare the sizes of both arrays
- @users = User. find ( : all )
- @users . select { | user | user. activated == 1 } . size == @users . size
- @users . all ? { | user | user. activated == 1 }
- # or even like this:
- @users . all ? ( & activated ) # provided that activated takes the value true / false, because 0 in ruby ​​is considered true
- # Take the first 5 items
- @array . take ( 5 )
- # Select random item
- @array . choice
- # Scatter items in random order
- @array . shuffle !
- # Get array element by its number
- # And this method is faster than @array [1]
- @array . at ( 1 )
- array = [ 1 , 1 , 2 , 2 , 3 , 4 , 5 ]
- array. count # => 7
- array. count ( 1 ) # counts the number of elements "1" => 2
- array. count { | p | p > 2 } # count elements by condition => 3
He just searches for all the cars in red. It is easy to contact him - Car.only_red. But the main drawback is that if you want to sort it all out (or add something like: limit => 5), you will have to either modify the method in the model, or use the standard find.
- class Car < ActiveRecord :: Base
- def self . only_red
- self . find ( : all ,: conditions => "color = 'red'" )
- end
- end
- class Car < ActiveRecord :: Base
- named_scope : red ,: conditions => 'color = "red"'
- end
And they can be combined. First, add a new scope that will allow users who own the machines to be included in the request:
- Car. red . find ( : all ,: limit => 10 ,: order => "id DESC" )
- named_scope : with_users , include => : users
What can I change? Of course, (user.voted_for_karma? == false) looks incomprehensible, because you can simply remove the comparison with false using link_to_unless:
- link_to_if ( user. voted_for_karma ? == false ) , "Raise Karma ",: action => "add_karma"
You can make it even cooler - let us inform you that the user has already voted.
- link_to_unless user. voted_for_karma ?, "Raise Karma ",: action => "add_karma"
And you can also give another link if the user is not logged in, for example, redirect to registration:
- # link_name is here (not) used as the name of the original link
- link_to_unless ( user. voted_for_karma ?, "Raise Karma ",: action => "add_karma" ) { | link_name | "You have already voted" }
- link_to_if ( user. logged_in ?, "Create topic ",: action => "add_post" ) do | link_name |
- # if a logged-in user will click on the link, he will go to the login page
- link_to ( link_name,: controller => "users" ,: action => "login" )
- end
- <! - index.html.erb ->
- < ul id = "navbar" >
- < li > <% = link_to_unless_current ( "Home" , { : action = > "index"})%> < / li >
- < li > <% = link_to_unless_current ( "About Us" , { : action = > "about"})%> < / li >
- < / ul >
- <! - if we go to the About Us page, then in the html code we will see the following: ->
- < ul id = "navbar" >
- < li > <a href = "/ controller / index"> Home < / a > < / li >
- < li > About Us < / li >
- < / ul >
As you can see, to localize the title field in the news table, it’s enough to add the above entry to the localization file.
- ru:
- activerecord:
- errors :
- full_messages:
- rate:
- exists: "It is impossible to evaluate the same user twice"
- number_limit: "The score may take values ​​from -2 to 2"
- attributes:
- news:
- title: "Title"
- body: "text"
- article: "Article"
The message parameter takes the localization file, goes to the address activerecord.errors.full_messages, then at the specified in the model, and returns the localized string. Everything is quite simple. If you do not specify message, then the output will be a standard error phrase, but in my case, I replaced it with mine.
- class Rate < ActiveRecord :: Base
- validates_uniqueness_of : rate_owner_id,: message => "rate.exists"
- validates_inclusion_of : value ,: in => [ - 2 , - 1 , 1 , 2 ] ,: message => "rate.number_limit"
- end
Another useful method is verify. Judging by the name, it serves to ensure that the correct request has arrived at the controller. This is mainly for protection, and I strongly recommend using it for some methods.
- def search
- @users = User. find ( : all ,: conditions => "login LIKE '# {params [: q]}'" ,: limit => 30 )
- render : json => @users if request. xhr ?
- end
By the way, you should not paint the error in as much detail as possible - the main validation should take place in the model. Immediately we check the parameters, and swear if something is wrong.
- class UsersController < ApplicationController
- # We check the create method - it should only accept post requests and the specified parameters.
- # If something is wrong, then we redirect the user to the beginning, and add a flash error message.
- verify : only => : create ,: method => : post ,: params => [ : login ,: email,: name ] ,: redirect_to => : index ,: add_flash => { : error => 'Invalid request. Are you all right? " }
- end
By the way, you can use not only logger.debug, but also logger.info, logger.warn or even logger.fatal. In your own classes, you can write RAILS_DEFAULT_LOGGER.debug, because it will not respond to the phrase logger.debug.
- # inspect I call to conveniently display objects in the console
- logger. debug "users = # {users.inspect}"
After that, we need to either start the server with the - debugger parameter, or add
- class UsersController < ApplicationController
- def index
- @user = User. find_by_id ( params [ : id ] )
- role = @user . role
- debugger
- end
- end
in environment.rb. After that we update the index page in the browser - but it will stop and will not be loaded. It's time to look into the console, there is a debugger waiting for us.
- require 'ruby-debug'
- (rdb: 1) irb
- irb (# <UsersController: 0x1039edd20>): 001: 0> @user
- => # <User id: 1, login: "Vizakenjack">
- irb (# <UsersController: 0x1039edd20>): 001: 0> @ user.login = 'Admin'
- => "Admin">
Source: https://habr.com/ru/post/91194/
All Articles