Ask A Question

Notifications

You’re not receiving notifications from this thread.

How I can use extra params in habtm without so many troubles?

Jack asked in Rails

I have a model Station

class Station < ApplicationRecord
  validates :name, presence: true
  has_many :ways
  has_many :routes, through: :ways
  has_and_belongs_to_many :tickets

  def update_index_number(route, index_number)
    way = way(route)
        way.update(index_number: index_number) if way
  end

  def index_number_in(route)
    way(route).try(:index_number)
  end

  protected
  def way(route)
    @way ||= ways.where(route: route).first
  end
end

, Route model

class Route < ApplicationRecord
  validates :name, presence: true
  has_many :trains
  has_many :ways
  has_many :stations, through: :ways
end

and Way

class Way < ApplicationRecord
  belongs_to :station
  belongs_to :route
end

All migrations:

class CreateStations < ActiveRecord::Migration[5.2]
  def change
    create_table :stations do |t|
      t.string :name
    end
  end
end

class CreateRoutes < ActiveRecord::Migration[5.2]
  def change
    create_table :routes do |t|
      t.string :name
    end
  end
end

class WayJoinTable < ActiveRecord::Migration[5.2]
  def change
    create_table :ways, id: false do |t|
      t.belongs_to :station, index: true
      t.belongs_to :route, index: true
      t.integer :index_number, default: 10, null: false
    end
  end
end

But I can NOT write the :index_number!!

I also have this in routes:

  resources :stations do
    patch :update_index_number, on: :member
  end

This in station_controller:

  def update_index_number
    @station = Station.find(params[:id])
    @route = Route.find(params[:route_id])
    @station.update_index_number(@route, params[:index_number])
    redirect_to @route
  end

I get error:

ActiveRecord::StatementInvalid in StationsController#update_index_number
SQLite3::SQLException: no such column: ways.: UPDATE "ways" SET "index_number" = ? WHERE "ways"."" IS NULL
Extracted source (around line #12):
10 def update_index_number(route, index_number)
11     way = way(route)
12     way.update(index_number: index_number) if way
13 end

Please help somebody!
I belive in Rails and Community!

Reply

Issue solved.
create_table :ways, id: false do |t|
ways must have id
create_table :ways do |t|

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 79,047+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2023 GoRails, LLC. All rights reserved.