Rails创建帖子的“集合”

时间:2014-01-09 15:08:27

标签: ruby-on-rails model-view-controller ruby-on-rails-4

在我的rails应用中,用户可以创建设计。

Design.rb

belongs_to :user

User.rb

has_many :designs

我正在尝试创建一个新模型Look,以便用户可以创建外观。我设想这个工作的方式是当用户转到/looks/new时,他们有一个列表,列出了他们所喜欢的所有设计(我已经设置了该变量),表格格式正确用户可以通过的复选框,检查其中一些设计,然后单击“创建”。已检查的所有设计都将成为该Look的一部分。

由于我之前没有做过这种事情,我需要一些帮助来完成MVC的各个方面。

Look.rb

has_many :designs

Design.rb

belongs_to :looks # ??? Would the model be something different since technically when you create a design it doesn't belong to a look. 

看起来控制器

def new
  @designs = @user.favorites #This get's me all the designs that the particular user has favorited
  @look = Look.new # ??? Again, as I haven't set this sort of relation up before, I'm unsure.
end

请告诉我任何其他可以提供帮助的代码。我甚至可能会让这个声音变得更复杂。

2 个答案:

答案 0 :(得分:1)

此配置应该适合Justin:

class User < ActiveRecord::Base
  has_many :designs
  has_many :looks, through: :designs
end

class Design < ActiveRecord::Base
  belongs_to :user
  has_many :designs_looks
  has_many :looks, through: :designs_looks
end

class Look < ActiveRecord::Base
  has_many :designs_looks
  has_many :designs, through: :designs_looks
end

class DesignsLook < ActiveRecord::Base
  belongs_to :design
  belongs_to :look
  validates :design_id, presence: true
  validates :look_id, presence: true
end

我不知道您将来想做什么,但您可能想考虑将user_id放在DesignsLook模型上,因此您不需要复杂的连接查询来检索用户的所有外观。您还可以与所有用户实施共享设计

答案 1 :(得分:0)

您的用户有很多设计。新外观可以有很多设计。并且设计可以属于MANY外观,用户。闻起来像has many ..., :through http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

class User
  has_many :designs, through: :design_possesion
end
class Look
  has_many :designs, through: :look_designs
end
class Design
  has_many :look_designs, :design_possesion
end

当然,您必须创建相应的表格。

相关问题