You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails中如何在Controller跨Model访问数据?问题已解决

问题解决:在Rails的PomodoroCycle控制器中访问Pomodoro数据

更新说明:问题已解决

问题已经搞定啦!特别感谢Sebastian和Gabriel的帮助,修正后的代码如下:

控制器代码(app/controllers/pomodoro_cycles_controller.rb)

def pomodoro_collections
  { pomodoro_collection_0: Pomodoro.offset(0).first(100), pomodoro_collection_1: Pomodoro.offset(100).first(100) }
end

视图代码(app/views/pomodoro_cycles/show.html.erb)

<% @pomodoros_collections.each do |pomodoros_collection_hash| %>
<h2><%= pomodoros_collection_hash[0] %></h2>
<% pomodoros_collection_hash[1].each do |pomodoro| %>
<p>
<%= pomodoro.id %>
<%= pomodoro.color %>
</p>
<% end %>
<% end %>

重要提示:ActiveRecord中的#first方法本身就会返回对象数组,原来的Hash里错误地把结果又套了一层数组。直接用Pomodoro.offset(0).first(100)就能拿到Pomodoro对象的数组啦。


原问题描述

环境

  • Rails 5
  • PostgreSQL

问题

我没办法在PomodoroCycleController里正常访问Pomodoro.all的数据。我已经创建了Pomodoro和PomodoroCycle两个scaffold,需要在PomodoroCycle控制器中获取所有Pomodoro的数据,代码已经简化方便说明需求,也执行过bundle exec rails db:migrate了。本来期望在PomodoroCycle的Show视图(之后会放到Index视图)里显示所有Pomodoro数据,但浏览器里啥内容都没显示。

原代码

控制器原代码(app/controllers/pomodoro_cycles_controller.rb)

def show
  @pomodoros_collections = pomodoro_collections
end
def pomodoro_collections
  { pomodoro_collection_0 => [Pomodoro.offset(0).first(100)], pomodoro_collection_1 => [Pomodoro.offset(100).first(100)] }
end

视图原代码(app/views/pomodoro_cycles/show.html.erb)

<% @pomodoros_collections.each do |collection| %>
<p><%= collection %></p>
<% end %>

模型代码

PomodoroCycle模型(app/models/pomodoro_cycle.rb)

class PomodoroCycle < ApplicationRecord
  has_many :pomodoros
end

Pomodoro模型(app/models/pomodoro.rb)

class Pomodoro < ApplicationRecord
  belongs_to :pomodoro_cycle
end

迁移文件

更新后的迁移文件(db/migrate/20180103032759_create_pomodoro_cycles.rb)

class CreatePomodoroCycles < ActiveRecord::Migration[5.1]
  def change
    create_table :pomodoro_cycles do |t|
      t.string :activity
      t.integer :iteration
      t.integer :matrix_side_length
      t.datetime :created_at
      t.datetime :completed_at
      t.string :category_labels, array:true, default: []
      t.string :category_colors, array:true, default: []
      t.string :username
      t.timestamps
    end
    create_table :pomodoros do |t|
      t.belongs_to :pomodoro_cycle, index: true
      t.datetime :completed_at
      t.timestamps
    end
    add_index :pomodoros, :pomodoro_cycle_id
  end
end

未修改的迁移文件(db/migrate/20180103054425_create_pomodoros.rb)

class CreatePomodoros < ActiveRecord::Migration[5.1]
  def change
    create_table :pomodoros do |t|
      t.boolean :status
      t.string :category
      t.string :color
      t.datetime :completed_at
      t.string :username
      t.timestamps
    end
  end
end

内容的提问来源于stack exchange,提问作者clockworkpc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:40:02