solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 229 forks source link

virtus with strong_paramters #147

Closed boy-jer closed 11 years ago

boy-jer commented 11 years ago

I was wondering how to use strong_parameters with virtus gem

   class User
    include Virtus

    attribute :name, String, :coerce => false
   end

This is a stab for strong_parameters

   class User
     include ActiveModel::ForbiddenAttributesProtection
      include Virtus

    #attribute :name, String

    private
     def reblog_params
        params.require(:post).permit(:name)
     end
   end

Is this the right approach.

warmwaffles commented 11 years ago

Hey I use it constantly with strong_params. The whole idea of strong_params was to put that stuff in the controller an not on the model.

So here is what it should look like:

class User
  include Virtus
  include ActiveModel::ForbiddenAttributesProtection

  attribute :name, String
end
class UsersController < ApplicationController
  # ...

  def create
    # ...
    @user = User.new(user_params)
  end

  private

  def user_params
    params.require(:user).permit(:name)
  end
end

Except mine isn't a user model. It's a form object that creates the other models.

See: http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

solnic commented 11 years ago

So you're saying it works fine with Virtus? If yes I should probably close this issue.

warmwaffles commented 11 years ago

@solnic yes it works perfectly fine, params.require(:user).permit(:name) just returns back a hash of approved values.

solnic commented 11 years ago

OK cool :)