Search code examples
ruby-on-railsnested-formsfields-for

2 models in one form - how to save the data to respective tables?


I have this action for updating data:

  def edit
    @project = Project.find(params[:id])
    if @project.team
      @team = Team.find(@project.id)
    else
      @team = Team.new
    end
  end

Form:

= form_for @project do |f|
  ...
  = f.fields_for @team do |t|
  #if I use following: = f.fields_for :team do |t|, then the form inputs in this form are not displayed
    ...
  end

end

Models:

class Project < ActiveRecord::Base
  has_one :team
  accepts_nested_attributes_for :team
end

class Team < ActiveRecord::Base
  belongs_to :project
end

When I try to send the form, I get following error message

Team(#2501295380) expected, got ActiveSupport::HashWithIndifferentAccess(#2157764620)

I found similar posts here on SO, but no one helped me to solved this issue, that's why I'll be very grateful for every advice.

Many thanks


Solution

  • This is solving my issue:

      def edit
        @project = Project.find(params[:id])
        unless @project.team.nil?
          @project.team
        else
          @project.build_team
        end  
      end