Is it possible to require some strong parameters in Rails?

I am trying to do some server side validation for a form in Rails, and I would like certain fields to have a value. Here are the parameters of my controller:

private
def post_params
  params.require(:post).permit(:title, :text, :slug)
end

The problem is that the server simply allows these parameters - it does not require them, so you can send an absolutely empty form.

I understand that it params.requiretakes only one argument, and I tried to get around this without success:

private
def post_params
  params.require(:post, :title, :text, :slug)
end
# => wrong number of arguments (4 for 1)

private
def post_params
  all_params = [:post, :title, :text, :slug]
  params.require(all_params)
end
# => param is missing or the value is empty: [:post, :title, :text, :slug]

private
def post_params
  params.require(:post).require(:title).require(:text).require(:slug)
end
# => private method `require' called for "test thing":String

Is there a way to require a few strong parameters?

+4
source share
1 answer

. , , .. , params.require(:post).permit. permit, , . , :

def post_params
  params.require(:post).permit(:title, :text, :slug)
end

, :

{"post"=>{"title"=>'Test',"text"=>"Text test","slug"=>"any random name","type"=>"article"}}

, :

@post = Post.new(post_params)
@post.save

unpermitted parameters :type, type. , , . 4 .

, , :

class Post < ActiveRecord::Base
  validates_presence_of :title, :text, :slug
end

, title, text and slug . , .

:

Validations

,

+4

All Articles