Hassen
Hassen

Reputation: 7634

Rails: How to create an item on database using params with other data

I will try to be as simple as possible:

I have a form that gets products information (name, desc,... etc) that I would like to add to the Store products list (using model association: product belongs_to :store and store has_many :products).

In addition to that information, I would like to add a 'ON' status field to product table. Why? In the case the product owner would like to delete the product, the status goes to 'OFF' instead of destroying completely the product on database (for stats reasons, I have to keep data for 6 months.)

Here is my controller code:

# Create a new product for the actual company.
def create

    # Get store information.
    @store = Store.find_by_id session[:store_id]

    # Set new store product.
    product = @store.products.build(
        :name   => params[:product][:name],
        :desc   => params[:product][:desc],
        :url    => params[:product][:url],
        :status => 'ON'
        )

    if product.save
        redirect_to :back, :notice => 'Product successfully created.'
    else
        redirect_to :back, :alert => 'Something goes wrong.'
    end
end

I tried this shortcut, but it doesn't work:

product = @store.products.build(params, :status => 'ON')

My question, is how to add :status => 'ON' more elegantly than listing all params?

Thanks in advance.

Upvotes: 0

Views: 351

Answers (2)

grilix
grilix

Reputation: 5341

I think you can create a scope, say scope :enabled, conditions: {status: 'ON'}, and then you can do product = @store.products.enabled.build(params[:product]).

Upvotes: 1

denis.peplin
denis.peplin

Reputation: 9841

product = @store.products.build(params[:product])
product.status = 'ON'

Upvotes: 2

Related Questions