繁体   English   中英

在Rails中,如何验证特定控制器动作的模型?

[英]In Rails, how do I validate a model for a specific controller action?

如果我的模型如下所示:

class Post < ActiveRecord::Base
  validate :content, presence: true, on: :post_create_action
end

class PostsController < ApplicationController
  def create
   @post = Post.new(post_params)
   if @post.validate(:post_index_action) && @post.save
     redirect_to post_path(@post)
   end
  end
end

我知道@ post.validate不能像我在代码中描述的那样工作,但是我想知道在rails中是否可行。

您可以使用lambda此功能

模型/ post.rb

class Post < ActiveRecord::Base
  attr_accessor :post_creation
  validate :content, presence: true, if: lambda { self.post_creation == true }
end

controllers / posts_controller.rb

class PostsController < ApplicationController
  def create
   @post = Post.new(post_params)
   if @post.save
     redirect_to post_path(@post)
   else
     # Handle the validation errors
   end
  end

  private

  def post_params
    params.require(:post).permit(....).merge(post_creation: true)
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM