thank_you
thank_you

Reputation: 11107

Best Way to Create attributes for a Model Instance Object

I'm building a Rails server for the back-end of an iPhone app. Rails sends JSON to the front-end and I find myself doing something like this.

@user = User.find(1)

@user["status"] = "Some cool status"

render :json => @user.to_json

In my rspec tests I get

DEPRECATION WARNING: You're trying to create an attribute `status'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc.

I find it hard to find an appropriate alternative when it's just as easy to write an key value to the object that will be sent to the iPhone.

My question is what are some viable alternatives to what I'm trying to do and what's specially "wrong" with my code, besides the deprecation.

Upvotes: 1

Views: 449

Answers (1)

chrmod
chrmod

Reputation: 1445

You can convert your User object to hash and then mix additional keys to it:

class User
    def to_hash
        hash = {}
        instance_variables.each {|var| hash[var.to_s.delete("@")] = instance_variable_get(var) }
        hash
    end
end

And in your controller:

user = User.find(1)

user = user.to_hash

user[:status] = "Some cool status"

render :json => user.to_json

PS. No need to use instance variable @user as you render json anyway, local user variable is good enough.

Upvotes: 1

Related Questions