12

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.

3 Answers 3

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

Where @service is some your fetched Service

Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't answer the question at all.
2

This is how I would to solve this problem, preferably the first way.

current_user.orders.create!(params[:order].merge({ :service => @service }))

or

@service.orders.create!(params[:order].merge({ :user => current_user }))

Comments

0

I believe there's no 'magic' method for this case. But the logic is that you create an order when both user and service alredy exist, so service already holds user_id attribute and you should probably call build on service.orders:

@order = service.orders.build(params[:order].merge({ :user_id => service.user_id }))

1 Comment

While having user_id in Service model is not an option for me, it does make sense to do something similar to your answer. I prefer to merge service_id with order params and let the user build the order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.