I am extremely new to Ruby on Rails and while I am learning a lot fairly quickly, I have run into some issues with the proper syntax to interact between the Model and Controller layers. I ham working on a toy project that simulates a Jurassic Park management app. The db schema is as follows:
schema.rb
ActiveRecord::Schema.define(version: 2021_01_24_134125) do
create_table "cages", force: :cascade do |t|
t.string "name"
t.integer "max_capacity"
t.integer "number_of_dinosaurs"
t.string "power_status"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "dinosaurs", force: :cascade do |t|
t.string "name"
t.string "species"
t.string "diet_type"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "cage_id", null: false
t.index ["cage_id"], name: "index_dinosaurs_on_cage_id"
end
add_foreign_key "dinosaurs", "cages"
end
I have already written a few helper methods in both the dinosaur and cage models, but when I try to actually use them in the cage.controller or dinosaur.controller, I run into some issues with how to do so. These are the methods below:
cage.rb
class Cage < ApplicationRecord
has_many :dinosaurs
validates :name, :max_capacity, :power_status, presence: true
validates_uniqueness_of :name
def dinosaur_count
dinosaurs.count
end
def at_capacity?
return dinosaur_count == max_capacity
end
def is_powered_down?
return power_status == "DOWN"
end
def has_herbivore
dinosaurs.where(diet_type:"Herbivore").count > 0
end
def has_carnivore
dinosaurs.where(diet_type:"Carnivore").count > 0
end
def belongs_in_cage(diet)
return true if dinosaur_count == 0
return false if diet != 'Carnivore' && has_carnivore
return false if diet != 'Herbivore' && has_herbivore
return true if dinosaurs.where(diet_type: diet).count > 0
return false
end
def has_dinosaurs?
return dinosaur_count > 0
end
end
dinosaur.rb
class Dinosaur < ApplicationRecord
belongs_to :cage
validates :name, :species, :diet_type, :cage_id, presence: true
validates_uniqueness_of :name
def set_cage(c)
return false if c.at_capacity?
cage = c
end
def move_dino_to_powered_down_cage(c)
return false if c.is_powered_down?
cage = c
end
def is_herbivore?
return diet_type == "Herbivore"
end
def is_carnivore?
return diet_type == "Carnivore"
end
end
I have tried something like this in the cage.controller update, but it is ignored when updating a cage's power status for example.
if @cage.is_powered_down? == "true"
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @cage.errors, status: :unprocessable_entity }
else
format.html { redirect_to @cage, notice: "Cage was successfully updated." }
format.json { render :show, status: :ok, location: @cage }
end
Would anyone be able to assist me with this at all?
question from:
https://stackoverflow.com/questions/65892150/how-to-use-ruby-on-rails-model-methods-in-controller-layer