A long time Java developer - new to ror - I am building a JSON REST API in Rails 4, and I have run into issues using strong parameters. When I perform an HTTP POST request to one of my endpoints, I would like for my controller to require the main object, require some of its attributes, and, if certain other attributes are present, for it to also return those. Seeing as those require and permit methods return hashes, I am wondering what the best practice is for both permitting and requiring certain attributes of the same object. Should I perhaps merge the two hashes? Thank you very much for your input, as I have spent quite some time working on this issue.
To the best of my knowledge, I think the way to go is, that you only permit parameters in your controller, and then you perform attribute-validation in your model instead of directly in the controller on the parameters.
Strong parameters are only there to secure, that some ill-intended person does not hack your user-form and insert something like "role=admin".
As far as I know, the strong parameters functionality is not designed with the intend of actually requiring certain parameters to be present other than the single key containing the hash of attributes (like the model-key called user or likewise).
You can do validation in your model like this:
class User < ActiveRecord::Base
validates :email, :first_name, :last_name, presence: true
end
If you use something like simple_form, then the errors will even automatically be shown.
There is a guy here, that suggest multiple requires before the actual permitting. My personal opinion is that it is very ugly.
Strong parameters require multiple
def user_params
params.require(:user).require(:first_name)
params.require(:user).require(:last_name)
params.require(:user).permit(:first_name, :last_name)
end