我的应用程序中有3个模型-用户,帖子和评论。它们是这样关联的
- 用户可以发布信息
- 帖子属于用户
- 帖子可以有很多评论
- 评论属于用户
帖子模型
class Post < ApplicationRecord
belongs_to :user
has_many :comments,dependent: :destroy
validates :title,presence: true
validates :body,presence: true
end
用户模型
class User < ApplicationRecord
before_create { generate_token(:auth_token) }
before_save { self.email = email.downcase }
has_secure_password
has_many :posts
validates :name,presence: true
validates :email,presence: true,uniqueness: true
validates :password,confirmation: true
validates :password_confirmation,unless: Proc.new { |a| !a.new_record? && a.password.blank? }
def send_password_reset
generate_token(:reset_password_token)
self.reset_password_sent_at = Time.zone.now
save!
UserMailer.password_reset(self).deliver
end
def generate_token(column)
begin
self[column] = SecureRandom.urlsafe_base64
end while User.exists?(column => self[column])
end
end
评论模型
class Review < ApplicationRecord
belongs_to :user
end
用户控制器-显示方法
def show
@user = User.find(params[:id])
@posts = @user.posts
@reviews = @posts.reviews //This line shows error
end
我认为我在关联这些模型时出现了问题。 我想显示对该帖子发表的评论。我从帖子用户控制器显示...。但是当我尝试以相同方式显示评论时。我
我已经手动离开并发表评论以发布在Rails控制台中。
从架构中查看表
create_table "reviews",force: :cascade do |t|
t.string "comment"
t.string "user_id"
t.string "post_id"
t.datetime "created_at",precision: 6,null: false
t.datetime "updated_at",null: false
end