Rails模型验证不在自定义`create`操作上运行

时间:2014-01-03 16:40:58

标签: ruby-on-rails ruby-on-rails-3 validation ruby-on-rails-4

我有一个名为Post的模型,它存储了两种类型的帖子:问题和答案:

create_table "posts", :force => true do |t|
    t.integer       "post_type_id",  # 1 for Question, 2 for Answers
    t.integer       "parent_id"      # contains post_id of question if it's an answer
    t.text          "body", :null => false
end

create中的posts_controller操作用于创建问题。

所以我在这样的路线中创建了第二个创建动作,以便从答案形式处理Answers的创建:

resources :posts do
    post 'answer' => "posts#create_answer", as: :answer
end

问题是即使需要body字段,rails也不会为我的自定义create_answer控制器操作运行这些验证。

我可以使用空白body发布答案。对于正常的create操作(用于创建类型为问题的帖子),验证确实正常工作。

如何通过railed来为处理对象创建的自定义控制器操作运行模型验证?

PS。创建具有类型问题或答案的帖子有不同的业务逻辑......这就是为什么我需要为两者创建单独的创建操作。

更新

这是Post模型:

class Post < MyModel
    strip_attributes

    # relationships
    belongs_to :question, :class_name => 'Post', :foreign_key => 'parent_id'
    has_many   :answers,    :class_name => 'Post', :foreign_key => 'parent_id'

    # validations
    validates :post_type_id,        :presence => true,
                                    :numericality => true

    validates :parent_id,           :numericality => true,
                                    :allow_nil => true

    validates :user_id,             :presence => true,
                                    :numericality => true

    validates :body,                :presence => true
end

以下是create_answer操作:

def create_answer
    if @post = Post.friendly.find(params[:post_id])
        @answer = current_user.posts.new(
            :post_type_id => 2,
            :parent_id => @post.id,
            :body => post_params[:body])

        if @answer.save
            flash[:notice] = "Answer posted"
            redirect_to @post
        else
            logger.fatal "Answer saving failed"
            flash[:error] = "Something went wrong while posting your answer. We're looking into it."
            redirect_to :back
        end
    end
end

0 个答案:

没有答案