user1837021
user1837021

Reputation: 363

add a column value before saving item to database

Say user submits a form (creates new item in his account).

Before it goes to database - I want to do this:

params[:user] => current_user.id
# make a note of who is the owner of the item
# without people seing this or being able to change it themselves
# and only after that to save it to database

What's the best way to do it?

All I see in controller is this:

def create
    @item = Item.new(params[:item])
    ...
end

And I'm not sure how to change values under params[:item]

(current_user.id is Devise variable)

Tried to do this:

class Item < ActiveRecord::Base
    before_save :set_user

    protected

    def set_user
        self.user = current_user.id unless self.user
    end

end

And got an error:

undefined local variable or method `current_user'

Upvotes: 1

Views: 1349

Answers (1)

Jon Cairns
Jon Cairns

Reputation: 11951

It should be as simple as:

def create
    @item = Item.new(params[:item])
    @item.user = current_user
    #...
end

You're getting an undefined local variable or method current_user error as current_user is not available in the model context, only controller and views.

Upvotes: 4

Related Questions