sheepwalker
sheepwalker

Reputation: 1760

Sends parameters from controller to model with validation

I'm rails noob, and have been confused about sending params from controller to model. Say, my model has fields user_id_from and user_id_to, but to controller they came as to and from (for client-side simplify).

So in my controller I should modify fields for model with such ugly code:

UserRelationship.crate(:to => params[:user_id_to], :from => params[:user_id_from])

OR

this modification could be done some other way?

Upvotes: 0

Views: 414

Answers (1)

Unixmonkey
Unixmonkey

Reputation: 18784

Usually, the easiest thing to do is change the controller or form to send them in as params[:user_id_to] and params[:user_id_from] if possible.

But another way to make it easier could be to use alias_attribute

# app/models/user_relationship.rb
class UserRelationship < ActiveRecord::Base
  alias_attribute :to,   :user_id_to
  alias_attribute :from, :user_id_from
end

The longhand way to do this is also pretty simple:

def to=(val)
  self['user_id_to'] = val
end
def from=(val)
  self['user_id_from'] = val
end

Upvotes: 1

Related Questions