IhaveABadGirl
IhaveABadGirl

Reputation: 23

Setting the attribute of an object to be and attribute of another object

Im very new to Ruby on rails. I am trying to set a Product object (:userid) to the user object id (user.id). So far I have got this

class Product < ActiveRecord::Base
  before_create :set_userid
  def set_userid
    self.userid = User.new(params[:id])
  end
end

Is there any other way to set the value before the product object is created?

Upvotes: 0

Views: 68

Answers (2)

Piotr Kruczek
Piotr Kruczek

Reputation: 2390

Consider using associations to easily define relations between models using helpers like

Product    
belongs_to :user

User
has_many :products

Upvotes: 4

Your code won't works because model doesn't have access to params. So, you should assign User instance in action of your controller:

def your_action
  ...
  product = ...
  product.user = User.new(params[:id])

Upvotes: 1

Related Questions