Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Properly creating a model instance that has relation to multiple models

Let's say I have a standalone User model and Service model.

I also have a Order model that holds the orders created by an user for a service. I'm wondering how I could properly create an order entry in rails.

Here is how I'll create an order entry if it refers to only one other model, say user.

@order = current_user.orders.build(params[:order])
@order.save

Now how do I do that if order refers to multiple models (user and service)?

Assume that Order model has user_id and service_id attributes and all model objects are properly tagged with belongs_to and has_many relationships.

like image 700
Srini K Avatar asked Apr 22 '11 20:04

Srini K


1 Answers

@order = Order.new(params[:order])
@order.user = current_user
@order.service = @service
@order.save

Where @service is some your fetched Service

like image 53
fl00r Avatar answered Sep 28 '22 00:09

fl00r