Ruby on Rails - has_many in ruby on rails - ruby on rails tutorial - rails guides - rails tutorial - ruby rails
- A has_many association indicates a one-to-many connection with another model.
- This association generally is located on the other side of a belongs_to association.
- This association indicates that each instance of the model has zero or more instances of another model.
Example
class User < ApplicationRecord
has_many :posts
end
Clicking "Copy Code" button will copy the code into the clipboard - memory. Please paste(Ctrl+V) it in your destination. The code will get pasted. Happy coding from Wikitechy - ruby on rails tutorial - rails guides - ruby rails - rubyonrails - learn ruby on rails - team
- The table structure of Post would remain the same as in the belongs_to example: in contrast, User would not require any schema changes.
- If we want to get the list of all the published posts for the User, then we can add the following (i.e. we can add scopes to our association objects):
class User < ApplicationRecord
has_many :published_posts, -> { where("posts.published IS TRUE") }, class_name: "Post"
end