I created a template with a form, the data from which should appear in the mysql table.
Tell me, please, what should be in the controller and model, if, for example, the structure of the News table: id , title , content , author ?
I created a template with a form, the data from which should appear in the mysql table.
Tell me, please, what should be in the controller and model, if, for example, the structure of the News table: id , title , content , author ?
For such elementary things, use a generator:
rails g scaffold news title:string content:text author:reference If the author is an authorized user, or
rails g scaffold news title:string content:text author:string If the author is just a field, when sending a post.
It will create a controller, model, migration, and all views. author:reference indicates that author is a link to another model.
If the author is just a field, then nothing else needs to be done. Otherwise, you need to register a link in the news model:
belongs_to :author, class_name: "User" The relationship belongs_to indicates that each news is associated with one object, which can be obtained using the News.author method. The class_name parameter points to the model from which to take the object. If the model corresponds to the name of the connection ( Author ), then this parameter should not be specified, this is the default value.
In the user model, type feedback:
has_many :news The has_many relationship indicates that a single user is associated with many news items, which can be User.news using the User.news method User.news
And in the news controller, in the create method, add a line specifying the author of the news of the authorized user:
@news.author = <ваш объект авторизованного пользователя> One tip: for a news model, it is better to use a singular, plural, name, such as Announcement ( announcements ). This will make your code more intuitive and more beautiful. For example:
has_many :announcements One user is associated with many news, and their list is obtained by the method User.announcements . The name of the method in the plural. Rails knows that when specifying a plural number, when having a has_many relationship, you need to refer to the model in the singular, so it will turn to the Announcement model. In this case, we can get, for example, the latest news:
@announcement = Announcement.last The name of the variable in the singular, which tells us that it stores a single news item, and not a list of objects. It seems a trifle, but in case of a large amount of code it helps a lot.
You incorrectly approach the task. Read the Rails Guides , you can go directly to chapter 5.
Source: https://ru.stackoverflow.com/questions/296604/
All Articles