Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 Rails基本关联_Ruby On Rails 3_Ruby On Rails 3.1 - Fatal编程技术网

Ruby on rails 3 Rails基本关联

Ruby on rails 3 Rails基本关联,ruby-on-rails-3,ruby-on-rails-3.1,Ruby On Rails 3,Ruby On Rails 3.1,我正在尝试在rails中进行基本的模型关联。 基本上,我有一个列表表,其中存储了item_id和user_id 一个用户可以创建多个“列表项” 这是正确的方法吗 谢谢 class Item < ActiveRecord::Base has_many :users, :through => :lists end class User < ActiveRecord::Base has_many :items, :through => :lists end cla

我正在尝试在rails中进行基本的模型关联。 基本上,我有一个列表表,其中存储了item_id和user_id

一个用户可以创建多个“列表项”

这是正确的方法吗

谢谢

class Item < ActiveRecord::Base
  has_many :users, :through => :lists
end

class User < ActiveRecord::Base
  has_many :items, :through => :lists
end


class List < ActiveRecord::Base
  belongs_to :user
  belongs_to :item
end
class项:列表
结束
类用户:列表
结束
类列表
根据您想要达到的目标,您的解决方案是否正确。我看到以下情况:

  • 您希望在项目和用户之间创建n:m关联。因此,每个项目都可以被许多用户引用,每个用户引用许多项目。如果这是正确的上下文,那么您的解决方案就是正确的。有关这方面的更多信息,请参阅
  • 这种情况的另一种选择是使用。情况是一样的,但是谈论列表是没有意义的,因为它没有模型对象
  • 如果每个用户可能有许多列表,并且每个列表可能有许多项,那么您的解决方案将是错误的。这将不是将list作为连接表的n:m关联,而是两个1:n关系
  • 第三个示例的代码如下所示:

    class User < ActiveRecord::Base
      has_many :items, :through => :lists
      has_many :lists  
    end
    
    class List < ActiveRecord::Base
      has_many :items
      belongs_to :user
    end
    
    class Item < ActiveRecord::Base
      belongs_to :list
    end
    
    class用户:列表
    有很多:列表
    结束
    类列表
    在第一种解决方案中,您应该添加用户与列表的关系和要列表的项目的关系:

    class Item < ActiveRecord::Base
      has_many :lists
      has_many :users, :through => :lists
    end
    
    class User < ActiveRecord::Base
      has_many :lists
      has_many :items, :through => :lists
    end
    
    class项:列表
    结束
    类用户:列表
    结束
    
    如果“列表”实体确实是一个纯粹的关联/连接,也就是说,它没有自己固有的属性,那么您可以稍微简化一下,并使用has\u和\u-allown\u-to\u-many。那么你就不需要“列表”类了


    很多人会告诉你要始终使用has\u Many:through,但其他人(如我)会不同意-使用正确的工具来完成工作。

    是的,这会奏效。或者,您可以让项目
    属于:列表
    ,列表
    属于:用户
    有多个:项目
    ,用户
    有多个:列表
    class Item < ActiveRecord::Base
      has_and_belongs_to_many :users
    end
    
    class User < ActiveRecord::Base
      has_and_belongs_to_many :items
    end
    
    create_table :items_users, :id => false do |t|
      t.references :users, :items
    end