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.
routes.rb
scope path: "/admin" do
resources :posts
end
Allows routing from/admin/posts to the posts controller.
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.
routes.rb
scope module: "admin" do
resources :posts
end
Allows routing from/posts to the controller (Admin :: PostsController) in the Admin namespace.
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].
References Ruby on Rails API Rails Guide
Recommended Posts