Here is my current database setup: https://gist.github.com/8dfad988528fc9fbc394
I want to create a host only if one like it does not already exist (matching on :host and :port), then I want to add the relation for that host into the relations table.
Multiple users can own a single host, or a single host can belong to multiple users. My current database setup works and the relations are created, I’m just not sure how to do this in Rails gracefully. I’ve tested up to this point by entering values into the database by hand, like so:
@host = Host.find_or_create_by_host(host: params[:host], port: params[:port])
@user = User.find(1)
@user.relation.create(user_id: @user.id, host_id: @host.id)
Is there a better way to do this, if so what would that be.
Solution
@host = Host.where(host: params[:host], port: params[:port]).first_or_create
@host.users << User.find(1)
Simply use this, the ActiveRecord takes care of the relation: