如何在控制器层的 Rails 模型方法上使用 Ruby

How to use Ruby on Rails Model methods in Controller layer

我在 Rails 上对 Ruby 非常陌生,虽然我学得很快,但我 运行 遇到了一些关于模型之间交互的正确语法的问题和控制器层。我正在从事一个模拟侏罗纪公园管理应用程序的玩具项目。数据库架构如下:

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.controller 或 dinosaur.controller 中实际使用它们时,我 运行 进入如何这样做的一些问题。这些是以下方法:

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

我在 cage.controller 更新中尝试过类似的操作,但是在更新笼子的电源状态时它被忽略了。

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?