【问题标题】:I am struggling with associations with my models on ruby on rails我正在努力与我的模型在 ruby​​ on rails 上的关联
【发布时间】:2014-10-15 15:21:04
【问题描述】:

我创建了一个名为 imdb 的新 Rails 应用程序。我创建了两个模型(通过脚手架),称为UserMovie。我在终端运行了这个。

rails g scaffold Movie title:string review:text location:string

rails g scaffold User name:string password_digest:string

我发现很难想象可以在我的应用程序中实现的关联,并且需要一些帮助来解决这个问题。

我们有这些关联:

belongs_to,
has_one,
has_many,
has_many :through,
has_one :through,
has_and_belongs_to_many

到目前为止,我一直认为一个“用户”可以有很多“电影”,一个“电影”可以有很多“用户”,但不幸的是我的大脑一片空白!非常感谢您的帮助。

谢谢。

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 associations scaffolding


【解决方案1】:

这可能会让您感到困惑,因为电影和用户之间可能没有任何直接关系。如果您有第三个模型 Review 这可能更有意义。

class Movie < ActiveRecord::Base
  has_many :reviews, inverse_of: movie
end

class User < ActiveRecord::Base
  has_many :reviews, inverse_of: user
end

class Review < ActiveRecord::Base
  belongs_to :movie  
  belongs_to :user
end

【讨论】:

    【解决方案2】:

    我会创建类似的东西

    Class User
    has_many :movies
    
    Class Movie
    Belong_to :users
    has_many :reviews :as => :reviewable
    
    
    class Review
    Belongs_to :movie
    or
    belongs_to :user
    belongs_to :reviewable :polymorphic => true (this way this class can be reused later for more than movies and always written by user) 
    has_many :comments :as => :commentable etc.
    

    【讨论】:

      【解决方案3】:

      这类似于一个用户可能有多个角色的情况,当您使用权限(管理员、用户、访客、禁止等...)时,一个角色可能有多个用户。

      如果我想创建一个可以独立地与其他模型关联使用的模型,我会使用多态关联作为 Richardlonesteen。例如:我希望用户为书籍和电影撰写评论,但评论属于书籍或电影,而不属于两者。

      您的解决方案是使用has_many :through 关联。您将拥有 3 个模型:用户、电影,以及将用户和电影之间的关系联系起来的另一个模型。例如,我们将这第三种模型称为筛选,但它可以是其他任何东西。创建筛选模型时,您还需要使用两列 user_id:integer movie_id:integer 进行迁移,并确保对它们都进行索引。

      你的用户.rb

      class User < ActiveRecord::Base
        has_many :movies, :through => :screenings
        has_many :screenings
        attr_accessible :username
      end
      

      你的电影.rb

      class Movie < ActiveRecord::Base
        has_many :users, through => :screenings
        has_many :screenings
        attr_accessible :name
      end
      

      您的筛选.rb

      class Screening < ActiveRecord::Base
        # attributes are :user_id and :movie_id
        belongs_to :user
        belongs_to :movie
      end
      

      生成一个看起来像这样的关系表

      user_id | movie_id
      ------------------
          1   |    1
      ------------------
          1   |    2
      ------------------
          2   |    1
      ------------------
          3   |    2
      

      完成此设置后,您可以通过 @user.movies 获取用户的所有电影,反之亦然 @movie.users。 Rails 会知道如何找到关联。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多