Rails is a complex form editing several records with associations at once

I am developing a complex form that simultaneously updates several records of the same model, while updating the associated model. It looks something like this:

class Sport
  has_one :photo
end

class Photo
  belongs_to :sport
  acts_as_fleximage
end

class Page
  # the page is not related to either of the previous models
end

Just to get information about background information, the page model is a general model for which users can create as many (CMS) as possible. In addition, during registration they receive a small number of mandatory "system" pages. When they try to edit the system page, the form is slightly different from the general form of the page.

- "". ( "" ) ( "" ).

, , , . , , :

:id => 1
:page => {"title"=>"Our sports"}
:sport => {
  "1" => {
    "description" => "<p>I love playing hockey...</p>"
    "photo_attributes" => {
      "image_file" => #<File:/tmp/RackMultipart20100126-955-k0gxu8-0>,
      "description" => "Me in my hockey kit"
    }
  },
  "2" => { #more of the same}
}

, , / :

def update_sports_page
  @page = Page.find params[:id]
  @page.update_attributes params[:page]
  Sport.update(params[:sport].keys, params[:sport].values)
  redirect_to #etc
end

, , , EXCEPT, , , sport_id NULL.

, .

- , ?

(ps, , , fleximage )

+3
1

, , , : depend = > : nullify , : depend = > : destroy.

, :

class Photo
  belongs_to :sport,
    :dependent => :destroy
end

.

, .

def update_sports_page
  @page = Page.find params[:id]
  @page.update_attributes params[:page]

  params[:sport].each do |sport_id, sport_params|
    sport = Sport.find(sport_id)
    sport.update_attributes!(sport_params)
  end

  redirect_to #etc
rescue ActiveRecord::RecordNotFound
  render(:partial => 'page_not_found', :status => :not_found)
rescue ActiveRecord::RecordInvalid
  render(:action => 'edit')
end

. " ", , . , .

+1

Source: https://habr.com/ru/post/1730041/


All Articles