This is the first post. I learned Ruby on Rails at school and had a refactoring curriculum, but at that point I was desperate to complete it, and I hadn't refactored it, so this time I moved the controller logic to Model and made the controller cleaner. I will write the method.
It refers to the state of the controller where the number of lines of the controller itself is large and it is difficult to follow the processing flow (simply speaking, the visibility is bad). At school, I wrote all the logic in the Controller without being aware of it at all, but I am still fighting with the personal application Fat Controller because I want to get closer to the code at the practical level (laughs).
First of all, let's feel like moving all the logic of the controller that has expanded enormously to Model. Actions are sufficient for public methods described in Controller.
And I think that there is basically no problem with Model as the destination to move the logic.
Before carving ↓
def show @useritems = Item.includes(:images).where(user_id:(current_user.id)).order(id: "DESC") if user_signed_in? end
Since the authentication function is implemented using devise, the id of the currently logged-in user can be obtained with "current_user.id". In other words, I want to pull the user's item information to the user's My Page (show action) that is currently logged in. However, this data acquisition, in fact, is also used in the index action of "items.controller.rb". So I would like to define a method in Model and put together a description to get the user's item.
First of all, Controller
def show @useritems = Item.user_items_get(current_user.id) if user_signed_in? end
Since "current_user" cannot be used on the Model side, pass it as an argument.
def self.user_items_get(user_bigint) Item.includes(:images).where(user_id:(user_bigint)).order(id: "DESC") end
By doing this, even the index action of ItemController
def index @useritems = Item.user_items_get(current_user.id).limit(10) if user_signed_in? end
It can be used like this.
When it comes to writing a method in Model and calling it in Controller, beginners tend to feel that it is a big deal, but it is important to make Controller clean, so please use it. (The number of lines in this example hasn't decreased ... lol)