Rails 4 has_many:通过与:source的关联

时间:2015-11-25 01:35:44

标签: ruby-on-rails ruby-on-rails-4 many-to-many has-many-through

我正在按照以下链接中的答案来设置我的Rails 4应用程序上的多个关系。 (这里是rails的新手。) Implement "Add to favorites" in Rails 3 & 4

我有用户和练习,我希望用户能够有最喜欢的练习。我创建了一个名为FavoriteExercise的连接表,其中user_id和exercise_id为列。我已经填充了它,它似乎工作正常,但我无法用它来直接调用我的收藏夹。

意思是,我想输入:
user.favorite =已被收藏的练习#list

当我尝试在浏览器中加载该列表时出现此错误:

SQLite3::SQLException: no such column: exercises.favorite_exercise_id: 

SELECT "exercises".* FROM "exercises" INNER JOIN "favorite_exercises" 
ON "exercises"."favorite_exercise_id" = "favorite_exercises"."id"
WHERE > "favorite_exercises"."user_id" = ?

我的模特:

class User < ActiveRecord::Base
  has_many :workouts    
  has_many :exercises   
  has_many :favorite_exercises
  has_many :favorites, through: :favorite_exercises, source: :exercises

class Exercise < ActiveRecord::Base
  belongs_to :user
  has_many :workouts, :through => :exercises_workouts
  has_many :favorites
  has_many :favorited_by, through: :favorite_exercises, source: :exercises

class FavoriteExercise < ActiveRecord::Base
  has_many :exercises
  has_many :users

我只是尝试将FavoriteExercise切换为'belongs_to'而不是'has_many,因为看起来这应该是应该去的方式?但后来我得到了这个错误:

uninitialized constant User::Exercises

试着找出如何设置表格和关联,以便我可以在用户上调用.favorites并获取所有收藏夹。

2 个答案:

答案 0 :(得分:0)

您只需简化模型逻辑,如下所示:

class User < ActiveRecord::Base
  has_many :workouts
  has_many :exercises     
  has_many :favorite_exercises
  has_many :favorites, through: :favorite_exercises, class_name: "Exercise"

class Exercise < ActiveRecord::Base
  belongs_to :user
  has_many :workouts, :through => :exercises_workouts
  has_many :favorite_exercises
  has_many :favorited_by, through: :favorite_exercises, class_name: "User"

class FavoriteExercise < ActiveRecord::Base
  belongs_to :favorited_by
  belongs_to :favorite

然后,您可以在User / Excercise实例中调用user.excercisesexcercise.users

user.excercises =已被收藏的练习列表

这是你想要的多对多关系吗?

答案 1 :(得分:0)

如果你想要用户的练习列表,并且同样是用户最喜欢的练习列表,那么我认为你的连接表应该只是users_exercises,其中它将列出用户的所有练习。要列出最喜欢的练习,只需添加一个布尔字段,指示练习是否是用户最喜欢的,并添加:范围以获得所有喜爱的练习。

所以在您的迁移文件中:

users_exercises应该有user_id, exercise_id, is_favorite

然后在你的模型中:

class User < ActiveRecord::Base
  has_many :workouts    
  has_many :users_exercises
  has_many :exercises, through: :users_exercises

  scope :favorite_exercises, -> {
    joins(:users_exercises).
    where("users_exercises.is_favorite = ?", true)
  }

class Exercise < ActiveRecord::Base
  has_many :workouts, :through => :exercises_workouts
  has_many :users_exercises
  has_many :users, through: :users_exercises

class UsersExercise < ActiveRecord::Base
  belongs_to :exercise
  belongs_to :user