← Back to Upcase

Write data into db through association

(alex) #1

I have two entities Project and Domain.
How can I code this:

domain has_many :project
project belongs_to :domain # so I have a domain_id column in `project`. 

Because I have a form_for on the project index, it is a bit different saving the domain_id(project table) and save data into domain table.

I don’t need the code I just need some pointers, I already have a working solution, but the models associations are opposite to what I wrote above, and I have nested forms, and to get the domain value I have to do this.

def domain_params
    params.require(: project).permit!(:name, :domain_id, :domain).tap do |whitelisted|
    whitelisted[:domain] = params[:project][:domain]

(Jason Draper) #2

Hi @Alex. I’m not sure I completely understand the domain so forgive me if I’m answering the wrong question but typically when dealing with nested forms like this I would recommend using a FormObject. The form object should wrap up the parts from each of the models you’re trying to work with and make it a bit easier to handle.

Here are a few good posts on the subject:

http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ (See #3)