我对Ruby on Rails非常陌生,虽然我学得很快,但我遇到了一些关于模型层和控制器层之间交互的正确语法的问题。我正在研究一个玩具项目,模拟侏罗纪公园管理应用程序。数据库模式如下:
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
我已经在恐龙模型和笼子模型中编写了一些辅助方法,但是当我尝试在笼子中实际使用它们时。控制器还是恐龙。控制器,我遇到了一些问题,如何做到这一点。这些方法如下:
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
我在笼子里试过类似的东西。控制器更新,但在更新笼子的电源状态时被忽略,例如
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
有谁能帮我做这件事吗?啊,是的,@cage.is_powered_down?
返回一个布尔值,所以你可以这样做:
if @cage.is_powered_down?