[英]How to get all messages from a blog in Rails
I am trying to practice my syntax with rails.我正在尝试用 Rails 练习我的语法。
I have 3 tables which is:我有 3 张桌子,它们是:
Blog:博客:
class Blog < ActiveRecord::Base
# Relationships
has_many :owners
has_many :posts
has_many :users, through: :owners
has_many :users_posts, through: :posts, source: :user
# Validations
validates :name, :description, presence: true
end
Post:邮政:
class Post < ActiveRecord::Base
# Relationships
belongs_to :blog
belongs_to :user
has_many :messages, dependent: :destroy
# Validation
validates :title, :content, presence: true, length: { minimum: 3 }
# Update Method
after_update :updated
def updated
puts "Got Updated"
end
end
And Message:和消息:
class Message < ActiveRecord::Base
belongs_to :post
belongs_to :user
# Validation
validates :author, :message, presence: true, length: { minimum: 3 }
end
I'm trying with the terminal by rails console
我正在尝试通过
rails console
使用终端
and I'm trying to get all the messages from the blog id 5 by this command我正在尝试通过此命令从博客 id 5 获取所有消息
Blog.find(5).posts.messages
it's not working but when I tried Blog.find(5).posts.first.messages
=> It showed me the message. Blog.find(5).posts.messages
它不起作用但是当我尝试Blog.find(5).posts.first.messages
=> 它向我显示了消息。 So is there anyway I can get all the message from blog 5 in 1 command?那么无论如何我可以从博客 5 in 1 命令中获取所有消息吗?
Two ways:两种方式:
1) with an association. 1) 与协会。 Add to blog
添加到博客
has_many :messages, through: :posts
and then接着
messages = Blog.find(5).messages
2) with a query, without a specific association for it 2)有一个查询,没有特定的关联
messages = Message.joins(post: :blog).where(blogs: { id: 5 })
Add 1 more association to Blog class has_many:messages, through: :posts
and then you'll be able to access Blog.find(5).messages
再添加 1 个关联到 Blog class
has_many:messages, through: :posts
然后你就可以访问Blog.find(5).messages
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.