我有这些模型:Post,TextPost和PhotoPost,我使用多态关联。
您可以找到这三个模型here或查看以下内容。
post.rb
class Post < ActiveRecord::Base
belongs_to :user
default_scope { order ("created_at DESC")}
belongs_to :content, polymorphic: true
has_reputation :votes, source: :user, aggregated_by: :sum
end
photo_post.rb
class PhotoPost < ActiveRecord::Base
has_attached_file :image, styles: {
post: "200x200>"
}
end
text_post.rb
class TextPost < ActiveRecord::Base
attr_accessible :body
end
我想要的是,当用户分别提交text_post或photo_post时,验证是否存在:body和:image。到目前为止,我发现我必须使用validates_associated。 完整项目可在Github上找到。
我已经做了很多实验,以了解validates_associated的工作原理并在线搜索示例,但我不知道发生了什么。
(如果您需要更多信息,请告诉我) 非常感谢任何帮助/指导。
答案 0 :(得分:1)
我认为对于初学者来说,这三种模型之间需要有某种形式的关联。您有Post
,PhotoPost
和TextPost
。由于帖子可以有type
个帖子。还要记住rails中的type
是保留字。但无论如何,你的模型应该如下:
class Post< ActiveRecord::Base
belongs_to :postable, polymorphic: true
end
class PhotoPost < ActiveRecord::Base
has_many :posts, as: :postable
end
class TextPost < ActiveRecord::Base
has_many :posts, as: :postable
end
从查看您提供的代码段开始,它不会显示任何多态关联的设置。关于验证多态关联的关联,您可能想要阅读这个答案:Validate presence of polymorphic parent。此外,也可能想阅读这篇文章:Validating a polymorphic association for a new record。 validate_associated
验证帮助程序的目的只是确保两个记录之间的关联有效或者将它们放在works
中。在您的情况下,如果您要使用该验证助手。这不是你想要的,因为所有这些都是验证两个模型之间的关联。看到我提供的第二个链接这是我相信你所追求的。
同样在您的控制器中,您需要建立模型之间的关系。所以在你的控制器我认为你可以在你的new
行动中找到类似的内容:
def new
@Post = Postfind(params[:id])
@PhotoPost = @post.photoposts.build
@TextPost = @post.textposts.build
end