Main functions of scope method

Not only is it difficult to infer the function from the scope method and the name, but also the scenes that appear are various and complicated, so I organized them.

1 scope(name, body, &block) Generate a class method to query the database for objects with specific conditions. Call with model. It can be used when you want to simplify the description of controller actions.

shirt.rb


class Shirt < ActiveRecord::Base
  scope :red, -> { where(color: 'red') }
end

↓ Synonymous

shirt.rb


class Shirt < ActiveRecord::Base
  def self.red
    where(color: 'red')
  end
end

The Proc object returned by the lambda expression "->" that receives the symbol representing the method name as the first argument and the block {where ..} indicating the search condition as the argument is passed. -> Is the same even if you replace it with lambda.

2 scope(*args) Processing related to routing. It can be used when you want to customize resource routing. Call it in routes.rb. There are various usages and notations, so some excerpts.

2-1 Add a prefix to the path

routes.rb


scope path: "/admin" do
  resources :posts
end

Allows routing from/admin/posts to the posts controller.

2-2 Add a prefix to the named routing helper

routes.rb


scope as: "secret" do
  resources :posts
end

Helpers such as secret_posts_path and new_secret_posts_path are generated and assigned to/posts and/posts/new respectively.

2-3 Routing to a controller in a certain namespace

routes.rb


scope module: "admin" do
  resources :posts
end

Allows routing from/posts to the controller (Admin :: PostsController) in the Admin namespace.

3 Option “: scope” in form helper form_with

Prefix the input field name

ruby:new.html.erb


<%= form_with scope: :post, url: posts_path do |form| %>
  <%= form.text_field :title %>
<% end %>

# =>
<form action="/posts" method="post" data-remote="true">
  <input type="text" name="post[title]">
</form>

The post passed with the: scope option becomes the field name in which the attribute name title passed to text.field is nested. This will allow the controller to access params [: post] [: title]. If you pass an instance with the: model option, Rails will guess the scope and prefix it. If there is no scope information, the field name will be "title" and the controller will be able to access params [: title].

Summary

References Ruby on Rails API Rails Guide

Recommended Posts

Main functions of scope method
definition of ruby method
Practice of binary search method
Practice of linear search method
Summary of basic functions of ImageJ
Benefits of Java static method
About the role of the initialize method
[Rails] Implementation of many-to-many category functions
What kind of method is define_method?
[Basic knowledge of Java] Scope of variables