Update belongs_to Rails

I have the following relationships in my application.

class Row < ApplicationRecord
  belongs_to :skill, required: false
end

class Map < ApplicationRecord
  has_many :rows
end

class Skill < ApplicationRecord
  has_many :rows
  has_many :maps, through: :rows
end

When I create a new skill, I would like to update that Row's skill_id to the id of the skill that was just created by the following form.

<%= form_with(model: skill, local: true, url: row_skills_path) do |form| %>
  <div class="form-group">
    <%= form.label :skills %>
    <%= form.text_field :skills, class: 'form-control' %>
  </div>

  <%= form.submit 'Submit', class: 'btn btn-primary' %>
<% end %>

The skills controller is very straight forward.

class SkillsController < ApplicationController
  def new
    @skill = Skill.new
  end

  def create
    @skill = Skill.new(skill_params)

    respond_to do |format|
      if @skill.save
        format.html { redirect_to root_path, notice: 'Skill created.' }
      else
        format.html { render :new, notice: 'That shit failed.' }
      end
    end
  end

  private
    def skill_params
      params.require(:skill).permit(:skill_id, :skills)
    end
end

How can I update the Row's skill_id to the id of the skill that I just created using that form? Is it possible with the current relationships?

Update

Sorry, I also have a route that passes the Row id in the url if that helps.

resources :rows do
  resources :skills
end

1 answer

  • answered 2017-12-06 01:24 Trenton Tyler

    I have realized that this is not a good approach to how these models talk to each other. Instead I have decided to move to a model has_one relationship.