Creating a new object with multiple associations

This is a pretty simple question but I haven't heard an answer for it
yet.

Let's say that a Bid object belongs_to both an Auction and a User at
the same time. To create a new object I could do something like
user.bids.build which would associate the new bid with that user, or
auction.bids.build which would associate the new Bid with the Auction,
but I have no idea how to create a new bid that would be associate with
both at the same time. I can of course force-feed the new bid object
with the id of the Auction or User objects, but that is the stupid way
to do it.

This is probably a very newb question, but it never came up with me
before, and I don't remember reading about it anywhere.

Eleo wrote:

Let's say that a Bid object belongs_to both an Auction and a User at
the same time. To create a new object I could do something like
user.bids.build which would associate the new bid with that user, or
auction.bids.build which would associate the new Bid with the Auction,
but I have no idea how to create a new bid that would be associate with
both at the same time. I can of course force-feed the new bid object
with the id of the Auction or User objects, but that is the stupid way
to do it.

Rather than explictly setting the Bid object's foreign key, either
add the Bid object to the collection or assign the associated object:

@auction.bids << @user.bids.build(params[:bid])

or

@bid = @user.bids.build(params[:bid])
@bid.auction = @auction
@bid.save!

Hmm I guess that will work. I like the first example because it uses
less lines.

I'd personally prefer something more semantically meaningful, thus
delegating the creation and association of a bid to the model domain:

class User < ...

  def bids_on(auction, bid_params)
    bid = Bid.new(bid_params)
    bid.auction = auction
    bid.user = self
    bid.save!
  end

end

And then in your controller:

@user.bids_on(auction, params[:bid])

This makes it immediately obvious what's going on, and the
implementation details are neatly encapsulated in the model.

Cheers,
Max