批量分配是正确的。params[:your_models_name]
您可以通过传递给YourModel.new
或来创建或更新模型YourModel.find(params[:id]).update_attributes params[:your_model]
。强参数是一种将可以批量分配的参数列入白名单的方法。
从指南:
class PeopleController < ActionController::Base
# Using "Person.create(params[:person])" would raise an
# ActiveModel::ForbiddenAttributes exception because it'd
# be using mass assignment without an explicit permit step.
# This is the recommended form:
def create
Person.create(person_params)
end
# This will pass with flying colors as long as there's a person key in the
# parameters, otherwise it'll raise an ActionController::MissingParameter
# exception, which will get caught by ActionController::Base and turned
# into a 400 Bad Request reply.
def update
redirect_to current_account.people.find(params[:id]).tap { |person|
person.update!(person_params)
}
end
private
# Using a private method to encapsulate the permissible parameters is
# just a good pattern since you'll be able to reuse the same permit
# list between create and update. Also, you can specialize this method
# with per-user checking of permissible attributes.
def person_params
params.require(:person).permit(:name, :age)
end
end
在上面的示例中,如果传入的参数如下所示:
{
person: {
name: 'bob',
age: 30,
admin: true
}
}
那么这个admin: true
参数就不会被分配给 bob 的 Person。
至于您的输入字段格式问题,它们应该出现在表单上。这不适合你吗?