When to use a private method in Rails?

I am not quite sure about the concept of a private method in rails, when and how to use it. Are there any rules? What are the differences between private and public as well as protected? For example, in the following example, why a private method is used here instead of the other two methods. Is it always better to use a private method for user input? Please enlighten me. Many thanks!

class PostsController < ApplicationController

def index
  @posts = Post.all.order("created_at DESC")
end

def new
 @post = Post.new
end

def create
 @post = Post.new(post_params)
  if @post.save
 redirect to @post
 else
  render 'new'
 end
end

def show
  @post = Post.find(params[:id])
end

private

def post_params
  params.require(:post).permit(:title, :body)
 end
end
+4
source share
2 answers

In the context of the Rails ActionController, the public methods of the controller class are exposed to the web server via Rails routes. You can define a route to the public methods of the class and use them as controller actions.

. , -.

. , , ether , , . .

, . , , ( , ).

+3

- .

, .

, .

ruby, -, .

, , , . - .

, , . . , Ruby , ? , .

+1

Source: https://habr.com/ru/post/1651128/


All Articles