exp*_*ner 6 ruby-1.9.2 ruby-on-rails-3.1
我有一个简单的案例,涉及两个模型类:
class Game < ActiveRecord::Base
has_many :snapshots
def initialize(params={})
# ...
end
end
class Snapshot < ActiveRecord::Base
belongs_to :game
def initialize(params={})
# ...
end
end
Run Code Online (Sandbox Code Playgroud)
通过这些迁移:
class CreateGames < ActiveRecord::Migration
def change
create_table :games do |t|
t.string :name
t.string :difficulty
t.string :status
t.timestamps
end
end
end
class CreateSnapshots < ActiveRecord::Migration
def change
create_table :snapshots do |t|
t.integer :game_id
t.integer :branch_mark
t.string :previous_state
t.integer :new_row
t.integer :new_column
t.integer :new_value
t.timestamps
end
end
end
Run Code Online (Sandbox Code Playgroud)
如果我尝试在rails控制台中创建一个Snapshot实例,请使用
Snapshot.new
Run Code Online (Sandbox Code Playgroud)
我明白了
(Object doesn't support #inspect)
Run Code Online (Sandbox Code Playgroud)
现在是好的一部分.如果我在snapshot.rb中注释掉initialize方法,那么Snapshot.new可以工作.为什么会这样?
顺便说一下,我使用的是Rails 3.1和Ruby 1.9.2
发生这种情况是因为您重写了initialize基类的方法(ActiveRecord :: Base).基类中定义的实例变量不会被初始化并且#inspect会失败.
要解决此问题,您需要调用super子类:
class Game < ActiveRecord::Base
has_many :snapshots
def initialize(params={})
super(params)
# ...
end
end
Run Code Online (Sandbox Code Playgroud)
当我在这样的模型中进行序列化时,我有这种症状;
serialize :column1, :column2
Run Code Online (Sandbox Code Playgroud)
需要像;
serialize :column1
serialize :column2
Run Code Online (Sandbox Code Playgroud)
小智 7
当我在joins.
例如,
Book.joins(:authors).first
Run Code Online (Sandbox Code Playgroud)
应该
Book.joins(:author).first
Run Code Online (Sandbox Code Playgroud)
假设 Book 模型belongs_to是 Author 模型。
| 归档时间: |
|
| 查看次数: |
12562 次 |
| 最近记录: |