antun
antun

Reputation: 2297

Rails migration for a model that references two models

My rails app has two models: User and Puzzle. I'm adding a Solve model which represents the solving of one specific puzzle by a user. The solve captures things like how quickly the user solved the puzzle. Ultimately, I only want to record the first time a user solves a specific puzzle, but for now I'm just trying to make sure I get the relationships between the models right.

Here's my migration for the new Solves table:

class CreateSolves < ActiveRecord::Migration[6.0]
  def change
    create_table :solves do |t|
      t.integer :time
      t.integer :attempts
      t.references :user
      t.references :puzzle

      t.timestamps
    end
  end
end

... and here is the Solve model:

class Solve < ApplicationRecord
  belongs_to :user
  has_many :puzzles, through: :user
end

Here is the create method in solves_controller.rb:

  def create
    @solve = Solve.new(solve_params)
    @solve.user = current_user
    @solve.puzzle = Puzzle.find(params["puzzle"]) # <----- THIS LINE

    respond_to do |format|
      if @solve.save
        format.json { render :show, status: :created }
      else
        format.json { render json: @solve.errors, status: :unprocessable_entity }
      end
    end
  end

When the user completes the puzzle, I send an ajax request to log their time, which includes the puzzle ID. Everything is working so far except the line labeled THIS LINE. When I added that, I get the error:

undefined method `puzzle=' for #Solve:0x00007fd6ed434830 Did you mean? puzzles= puzzles

I think that maybe I haven't set-up the correct relationship between the puzzle, user, and solve appropriately for my scenario.

Upvotes: 1

Views: 33

Answers (1)

max
max

Reputation: 102240

class User < ApplicationRecord
  has_many :solves
  has_many :puzzles, through: :solves 
end

class Solve < ApplicationRecord
  belongs_to :user
  belongs_to :puzzle
end

class Puzzle < ApplicationRecord
  has_many :solves
  has_many :users, through: :solves 
end

However Solve is a very awkward model name as it not actually a noun in English. Since models are things they should be nouns and not not verbs. Solution is a noun.

Upvotes: 2

Related Questions