Ruby on rails 在发布文本或图像之前进行验证
我正在开发一个自学Rails应用程序(可以找到源代码。我想在发布文本或图像之前验证内容的存在性: 下面是我的简历:Ruby on rails 在发布文本或图像之前进行验证,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我正在开发一个自学Rails应用程序(可以找到源代码。我想在发布文本或图像之前验证内容的存在性: 下面是我的简历: class Post < ActiveRecord::Base belongs_to :user default_scope { order ("created_at DESC")} belongs_to :content, polymorphic: true has_reputation :votes, source: :user, aggregated_
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
class PhotoPost < ActiveRecord::Base
has_attached_file :image, styles: {
post: "200x200>"
}
end
class TextPost < ActiveRecord::Base
attr_accessible :body
end
以及获取错误“未定义的#post:0x517c848>的方法'text_post'”
=>已使用的验证
validates :content, :presence => true
没有错误,但是创建的帖子没有文本
validates :body, :presence => true
以及获取错误“未定义的#Post:0x513e4a8>的方法'body'”
如果您需要任何其他信息,请让我知道,我会尽快提供
谢谢。似乎您的模型设置相当混乱,其中包含一些关键的缺失关系规则。例如,未使用的多态规则,以及用户和帖子之间存在许多关系,而帖子模型中没有用户id值的符号。我将如何设置它: User.rb
def User << ActiveRecord::Base
has_many :text_posts
has_many :photo_posts
end
def TextPost << ActiveRecord::Base
attr_accessible :body, :user_id
belongs_to :user
validates :body, :presence => true
end
def PhotoPost << ActiveRecord::Base
attr_accessible :image, :user_id
belongs_to :user
validates :file, :presence => true, :format => {
:with => %r{\.(gif|png|jpg)$}i,
:message => "must be a URL for GIF, JPG or PNG image."
}
end
def create
@text_post = current_user.text_posts.new(params[:text_post])
end
这更符合RubyonRails擅长的原则——您不应该为了创建新记录而编写大量代码
我建议您阅读一些Ruby on Rails标准和最佳实践。您不需要在仪表板模型中创建一个方法来创建新的TextPost或PhotoPost记录。这是一种非常混乱的方式;相反,您应该利用ActiveRecord关系的强大功能
我建议你去看看。他们有很多令人满意的内容。我有点困惑你在这里想要实现什么。为什么你有Post、TextPost和PhotoPost模型?PhotoPost和TextPost中没有关系结构,Post模型有一个多态关系,没有指向任何地方o“属于:内容,多态:真”,然后我使用content\u type和content\u id这个“结构”是由Thoughtbot.Ok的开发者Matthew Mongeau创建的。我似乎不明白为什么你需要用外国模型的方法创建一个新记录,即:
@dashboard.new\u text\u post…def new\u text\u post TextPost.new end
。你能解释一下这种方法背后的原因吗?我参加了一个研讨会,做了这一切。我真的无法解释然而,这种方法背后的原因是thoughbot拥有一个论坛,可以提供这样的解释。
<%= form_for @text_post do |f| %>
# ...
<% end %>
def create
@text_post = current_user.text_posts.new(params[:text_post])
end