I have home
controllers, with a index
view, and users
, with a new
view. How can I put the data from the new
view at index
so that the variables of the users
controller work there?
- oneguides.rubyonrails.org/… - Vetal4eg
2 answers
Each view takes data from the corresponding action of its controller. Therefore, if you go to work with the user in home # index, then define a variable for this in the index method of the home controller. You can also have several variables for different actions, like this:
class HomeController < ApplicationController def index @user = User.new #Объект, для нового пользователя. @user s = User.all #Список всех пользователей, если вы заходите вывести их в той же вьюхе. end
This method corresponds to the structure of Rails applications, so it’s better not to run out, but to use it. Otherwise, half of the actions that Rails could do for you, you have to implement yourself.
what kind of task is it? Do you want registration on the main page? then just in the routing file, specify root 'user # new', or do you want home # index to be the main one and what else should there be in addition to registration? then you can simply copy the user # new view and replace <% = form_for @user do | f | %> on <% = form_for User.new do | f | %> or copy the contents of the new method of the user controller to the home controller in the index method, then you do not need to replace anything
- oneand if you need a lot of where to apply the method from the controller, then it is better to implement it in the helper - stepofchange
- oneIn no case, not form_for User.new do | f |, only form_for @user do | f |, and @user to define in the controller. In the view there should be nothing but the conclusion, such is the agreement. All requests to the database and data processing takes the controller. - Risto
- I wrote that it is possible so, but it is possible and in the controller, it is possible still in a helper - stepofchange
- "either to the home controller in the index method copy the contents of the new method of the user controller" - isn't that what you wrote after me? - stepofchange
- @stepofchange, the bottom line is that only the second option is true. The whole essence of the simplicity of Rails in compliance with the naming convention and the structure of the application. The more such liberties you allow in your code, the harder it is to understand, and the more additional code you will have to write. What is normal for programming in a "pure" language can be a blunder for development using the framework. It itself enraged, until I settled down. - Risto