开发者

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

开发者 https://www.devze.com 2023-02-28 08:42 出处:网络
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 entr

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)?

开发者_JAVA百科

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.


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

Where @service is some your fetched Service


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 }))


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 }))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号