Notes posted to Ruby on Rails
RSS feed![Default_avatar_30](https://www.gravatar.com/avatar/aae8a096939117430c37280e7897f32c?size=30&default=http://apidock.com/images/default_avatar_30.png)
Generate Token
For generate a token, make this:
def generate_token self.token = SecureRandom.uuid end
SecureRandom return a number random and the uuid make this number be unique. This a good idea for use in shopping cart, for example
![Default_avatar_30](https://www.gravatar.com/avatar/b91a97f8a79bd0c29eb4e51431773aef?size=30&default=http://apidock.com/images/default_avatar_30.png)
Params of conditions
You can pass an proc for o callback with the conditions
before_action :initial_value, only: [:index, :show], unless: -> { @foo.nil? } before_action :initial_value, only: [:index, :show], if: -> { @foo }
![Default_avatar_30](https://www.gravatar.com/avatar/b91a97f8a79bd0c29eb4e51431773aef?size=30&default=http://apidock.com/images/default_avatar_30.png)
Params of conditions
You can pass an proc for o callback with the conditions
after_action :initial_value, only: [:index, :show], unless: -> { @foo.nil? } after_action :initial_value, only: [:index, :show], if: -> { @foo }
![Default_avatar_30](https://www.gravatar.com/avatar/ff7afae5b23125e25e18ad8c0404bd78?size=30&default=http://apidock.com/images/default_avatar_30.png)
the method to make 'day' disappear.
If you wanna show “year” and “month” only, you can use “order” to do it:
select_date(Date.current, order: [:year, :month])
That’s it.
![Default_avatar_30](https://www.gravatar.com/avatar/2e5e7d94324be62b6b328ecb067a1913?size=30&default=http://apidock.com/images/default_avatar_30.png)
Creates record by given attributes only if table is empty
This method first searches the table for ANY FIRST RECORD, not the one matching given attributes. If no record is found at all, it creates one using the specified attributes. This might be misunderstood in many cases.
![Default_avatar_30](https://www.gravatar.com/avatar/4478529eeeb6cb0970e3fcece19004cc?size=30&default=http://apidock.com/images/default_avatar_30.png)
What about Marshal remote code execution risks?
Good suggestion about using Marshal to avoid cycles, astgtciv, but what about the security risks of doing that?
See http://ruby-doc.org/core-2.2.2/Marshal.html where it states:
By design, ::load can deserialize almost any class loaded into the Ruby process. In many cases this can lead to remote code execution if the Marshal data is loaded from an untrusted source. As a result, ::load is not suitable as a general purpose serialization format and you should never unmarshal user supplied input or other untrusted data. If you need to deserialize untrusted data, use JSON or another serialization format that is only able to load simple, ‘primitive’ types such as String, Array, Hash, etc. Never allow user input to specify arbitrary types to deserialize into.
![Default_avatar_30](https://www.gravatar.com/avatar/17a4f6b25d9231c884da0fc6a5cda209?size=30&default=http://apidock.com/images/default_avatar_30.png)
Setting HTTP_REFERER
If your integration test is checking for correct behavior of a redirect to the request referer, you can set the referring path in the headers hash with syntax like:
patch update_user_role_path, { user: {role: "vip"} }, { 'HTTP_REFERER' => user_url } assert_redirected_to user_url
![Default_avatar_30](https://www.gravatar.com/avatar/ee66b348a67eed43e98d1ed8ad25f138?size=30&default=http://apidock.com/images/default_avatar_30.png)
Not quite opposite of new_record?
new_record? will not check if the record has been destroyed
![Default_avatar_30](https://www.gravatar.com/avatar/ee66b348a67eed43e98d1ed8ad25f138?size=30&default=http://apidock.com/images/default_avatar_30.png)
Not quite opposite of persisted?
persisted? will also check if the record has not been destroyed
![Default_avatar_30](https://www.gravatar.com/avatar/e2da7756e2fce664807547e1a312deac?size=30&default=http://apidock.com/images/default_avatar_30.png)
Rails 3.2.19
As Jebin reported, we are not getting the value in array format when we set the hidden_field_tag with an Array variable, instead it is a String that we are getting.
![Default_avatar_30](https://www.gravatar.com/avatar/096fbde2c2ad4278847dfe5b51cc5276?size=30&default=http://apidock.com/images/default_avatar_30.png)
instead of memoize
See this for deprecated github.com/rails/rails/commit/36253916b0b788d6ded56669d37c96ed05c92c5c
use
def something return @_var if defined? @_var # more code end
![Default_avatar_30](https://www.gravatar.com/avatar/0c91f58ffa7bbf4151cae13b5c8b9ccd?size=30&default=http://apidock.com/images/default_avatar_30.png)
Possible bug
Works as expected for non bang methods
> a={x:1, y:2, z:3} => {:x=>1, :y=>2, :z=>3} > a.slice(:y) => {:y=>2} > a.except(:y) => {:x=>1, :z=>3}
Bug on slice! it behaves like except!
> a.clone.slice!(:y) => {:x=>1, :z=>3} > a.clone.except!(:y) => {:x=>1, :z=>3}
slice! should return {:y=>2} and modify a to no longer have it
![Default_avatar_30](https://www.gravatar.com/avatar/25527b0a3534d78ab6cd6bdc921a71bf?size=30&default=http://apidock.com/images/default_avatar_30.png)
Multiple files
To use multiple file upload need to use variable_name[].
like this:
file_field_tag 'files[]', :multiple => true
and in controller:
if !params[ :files ].nil? params[ :files ].each{ |file| # do your staff } end
![Default_avatar_30](https://www.gravatar.com/avatar/dc3ee45902521594d55e2b8e3de5cf8e?size=30&default=http://apidock.com/images/default_avatar_30.png)
"Class methods on your model are automatically available on scopes."
The final example above – “Class methods on your model are automatically available on scopes.” – contains a subtle but vital change from earlier versions of the doc – namely, “pluck” (current example) vs “map” (old example). The former works, the latter does not. See http://github.com/rails/rails/issues/21943 for confirmation that the old documentation is incorrect, and for a workaround.
(Spoiler alert: Use
all.map(&:title)
instead of just
map(&:title)
in order to achieve the same effect.)
![Default_avatar_30](https://www.gravatar.com/avatar/dc3ee45902521594d55e2b8e3de5cf8e?size=30&default=http://apidock.com/images/default_avatar_30.png)
"Class methods on your model are automatically available on scopes."
The final example above – “Class methods on your model are automatically available on scopes.” – does not work as written. See http://github.com/rails/rails/issues/21943 for confirmation that the old documentation is incorrect, and for a workaround.
(Spoiler alert: Use
all.map(&:title)
instead of just
map(&:title)
in order to achieve the same effect.)
![Default_avatar_30](https://www.gravatar.com/avatar/c2713a4959692f16d27d2553fb06cc4b?size=30&default=http://apidock.com/images/default_avatar_30.png)
arel_table order by
More objected way how to achieve ORDOR BY .… DESC is like this :
class User < ActiveRecord::Base has_many :status_changes def latest_status_change status_changes .order(StatusChange.arel_table['created_at'].desc) .first end end class StatusChange < ActiverRecord::Base belongs_to :user end
resulting in:
SELECT "status_changes".* FROM "status_changes" WHERE "status_changes"."user_id" = 1 ORDER BY "status_changes"."created_at" DESC
Benefits:
-
you are strictly bound to Modelclass name => renaming table in model will not break the sql code (of if it will, it will explicitly break the syntax on Ruby level, not DB level)
-
you still have the benefit of explicitly saying what table.column the order should be
-
easier to re-factor parts to Query Objects
![Default_avatar_30](https://www.gravatar.com/avatar/39140673f8eaec4a3bdf5e76c1fac1eb?size=30&default=http://apidock.com/images/default_avatar_30.png)
Warning: prevents persistence but doesn't prevent setting
For example:
class Widget < ActiveRecord::Base attr_readonly :key end w = Widget.create! key: 'foo' w.update! key: 'bar' w.key #=> 'bar' w.reload.key #=> 'foo'
![Default_avatar_30](https://www.gravatar.com/avatar/8f0e3d1f20b788d067835a033d5d1f76?size=30&default=http://apidock.com/images/default_avatar_30.png)
Favicon generator
Hello, I suggest you to try this favicon generator and creator, http://onlinefavicon.com/ , you can create favicon using drawing tool or add picture jpg or other file and make 16x16 or 32x32 ICO file, also see the gallery with favicons from other users or download the same, at end you can read description how to set up favicon to your site!
![Default_avatar_30](https://www.gravatar.com/avatar/73daf7a1b23ead60646aa54da0c86f8b?size=30&default=http://apidock.com/images/default_avatar_30.png)
Text and Image together in #link_to
Code Example
link_to “Hello World #{ image_tag(‘web/worl.png’) }”.html_safe, some_path
![Default_avatar_30](https://www.gravatar.com/avatar/ee66b348a67eed43e98d1ed8ad25f138?size=30&default=http://apidock.com/images/default_avatar_30.png)
Using Arel
You can also use Arel.
For example:
class ArticlePage < ActiveRecord::Base belongs_to :article scope :published, -> { where.not(published_at: nil) } scope :all_ready, -> { select("every(workflow_state = 'ready') AS is_ready") } end class Article < ActiveRecord::Base has_many :article_pages def all_ready? ActiveRecord::Base.select_values(article_pages.all_ready,published) = 't' end end
![Default_avatar_30](https://www.gravatar.com/avatar/97b6ca901e910b0a5b111b8b06764e65?size=30&default=http://apidock.com/images/default_avatar_30.png)
Skip validation
update_all : skip validations, and will save the object to the database regardless of its validity. They should be used with caution.
![Default_avatar_30](https://www.gravatar.com/avatar/759f363eed45032976eaf20c75b2ed6a?size=30&default=http://apidock.com/images/default_avatar_30.png)
I would just use a validation instead of (the probably removed) :required
Just make sure you validate the presence of the association and not the foreign key, otherwise it will not work on new records.
The down side is that it will require the record in the cache, and will make a query otherwise. You can add `unless: :<foreign_key>?` If that’s a problem for you.
![Default_avatar_30](https://www.gravatar.com/avatar/f44d27aeb857362f7d7f57d18492b820?size=30&default=http://apidock.com/images/default_avatar_30.png)
Is :required still valid ?
I get this error when using :required => true
ArgumentError: Unknown key: :required. Valid keys are: :class_name, :class, :foreign_key, :validate, :autosave, :remote, :dependent, :primary_key, :inverse_of, :foreign_type, :polymorphic, :touch, :counter_cache
Is :required not a valid key anymore ?
![Default_avatar_30](https://www.gravatar.com/avatar/6e6e22d81a1f4f394f62301be40c2e20?size=30&default=http://apidock.com/images/default_avatar_30.png)
If you want to do a quick delete with no callbacks, use `delete_all`.
Person.where( thing: nil ).delete_all
![Default_avatar_30](https://www.gravatar.com/avatar/a3737b3ba27d3ec297a43538484a1cbe?size=30&default=http://apidock.com/images/default_avatar_30.png)
For supported arguments, see see match
As of July, 2015, the v4.2.1 doc says “see match[rdoc-ref:Base#match]” without a URL. I think you want this one: http://apidock.com/rails/ActionDispatch/Routing/Mapper/Base/match
![Default_avatar_30](https://www.gravatar.com/avatar/28cb41614f19603f2e4062ce44061415?size=30&default=http://apidock.com/images/default_avatar_30.png)
Usage with enum
With enum fields you must use integer values:
code
Model.update_all(type: Model.types[specific_type])
![Default_avatar_30](https://www.gravatar.com/avatar/35a3030cd2b4addc9ffe1bdbd529ecca?size=30&default=http://apidock.com/images/default_avatar_30.png)
Space before the opening [
In this example
Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
The array is a parameter, so a space is required before the opening [, which is equivalent to write like this
Post.find_by_sql(["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date])
![Default_avatar_30](https://www.gravatar.com/avatar/8ef46c3f25b9d06d1d903ec322fb4053?size=30&default=http://apidock.com/images/default_avatar_30.png)
Use :where or any defined scope before :find_or_create_by
You can chain find_or_create_by with :where, or any custom scope.
E.g.:
User.where(girls: true).find_or_create_by(first_name: ‘Scarlett’)
scope :celebrities, -> { where(celebrity: true) }
User.celebrities.create_with(last_name: ‘Johansson’).find_or_create_by(first_name: ‘Scarlett’)
![Default_avatar_30](https://www.gravatar.com/avatar/656b45e348cd0024af2d05e2ab7215d1?size=30&default=http://apidock.com/images/default_avatar_30.png)
Not a one-to-one-relationship
It’s incorrect to state that belongs_to “Specifies a one-to-one association with another class”.
If the inverse association is has_one then the model specifying belongs_to is the LHS of a zero/one-to-one relationship.
If the inverse association is has_many then the model specifying belongs_to is the LHS of a zero/many-to-one relationship.
Unless you know what the inverse association is, all you can assume is that instances of a class specifying a belongs_to association can be related to at most a single instance of the other class.
![Default_avatar_30](https://www.gravatar.com/avatar/096fbde2c2ad4278847dfe5b51cc5276?size=30&default=http://apidock.com/images/default_avatar_30.png)
render with variables
perient view
Code example
<%= render 'time_select', locals: { select_name: 'from_tiem'}%>
render view
Code example
<%= locals[:select_name] %>
not:
Code example
<%= local_assigns[:select_name] %>