【发布时间】:2017-04-30 14:57:58
【问题描述】:
我正在尝试在 Ruby on Rails 中创建一个应用程序,我可以:
创建会议(工作)
查看会议列表(工作中)
关注和取消关注会议(无效)
查看以下会议(不工作)
我早在 12 月就开始使用 Ruby on Rails,并使用 Micheal Hartl 的教程开始使用。在第 14 章 (https://www.railstutorial.org/book/following_users) 中,Micheal 介绍了关注和取消关注用户、低谷关系。
我正在尝试应用他的技术,但将其调整到一个模型和一个控制器之间存在关系的地方,以及有两个模型和两个控制器的地方。
一个控制器和模型是用户控制器和用户模型,另一个控制器和模型是会议控制器和会议模型。
我首先向用户模型添加活动关系,因为它是关注会议的一方
user.rb
has_many :active_relationships, class_name: "Relationship",
foreign_key: "follower_id",
dependent: :destroy
has_many :following, through: :active_relationships, source: :followed
我在会议模式中做了相反的事情,因为我是被关注的一方
Conference.rb
has_many :passive_relationships, class_name: "Relationship",
foreign_key: "followed_id",
dependent: :destroy
has_many :followers, through: :passive_relationships, source: :follower
为了清除结构,我在关系模型中添加了以下代码行
Relationship.rb
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "Conference"
validates :follower_id, presence: true
validates :followed_id, presence: true
当试图查看用户是否真的在关注会议时,用户模型中出现错误:
ActiveRecord::RecordNotUnique in RelationshipsController#create
SQLite3::ConstraintException: UNIQUE constraint failed: relationships.follower_id, relationships.followed_id: INSERT INTO "relationships" ("follower_id", "followed_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)
问题的根源在于:
app/models/user.rb:116:in `follow'
app/controllers/relationships_controller.rb:6:in `create'
我知道当记录无法插入时会出现问题,因为它会违反唯一性约束,但我不知道违反了什么唯一性约束。
现在第一个问题发生在 user.rb 中,此时正在用户和会议之间创建 active_relationship。
# Returns true if the current user is following the other user.
def following?(other_conference)
following.include?(other_user)
end
# Follows a conference.
def follow(other_conference)
active_relationships.create(followed_id: other_conference.id)
end
# Unfollows a conference.
def unfollow(other_conference)
active_relationships.find_by(followed_id: other_conference.id).destroy
end
第二个问题在Relationships_controller 中,current_user 应该关注会议。
def create
@conference = Conference.find(params[:followed_id])
current_user.follow(@conference)
respond_to do |format|
format.html { redirect_to @conference }
format.js
end
end
现在我不确定问题的原因是什么以及如何解决它。我希望我已经明确了我的问题以及我想要实现的目标。如果不是,我很乐意提供有关我的问题的更多信息。
【问题讨论】:
-
has_many :followings- 在 Rails 中创建关联和命名事物时要特别注意复数。
标签: ruby-on-rails ruby relationship