我有 3 个基本上是嵌套的模型。
class User < ActiveRecord::Base
attr_accessible :birthday, :name
has_one :advancement, :dependent => :destroy
accepts_nested_attributes_for :advancement
attr_accessible :advancement_attributes
end
class Advancement < ActiveRecord::Base
attr_accessible :user_id, :rank_name
belongs_to :user
has_one :rank, :dependent => :destroy
accepts_nested_attributes_for :_rank
attr_accessible :rank_attributes
end
class Rank < ActiveRecord::Base
attr_accessible :advancement_id, :one_li, :one_pi, :one_date, ...
belongs_to :advancement
end
这是我用来创建模型的控制器代码。
class UsersController < ApplicationController
def new
@user = User.new
@user.advancement = Advancement.new
@user.advancement.rank = Rank.new
respond_to do |format|
format.html # new.html.erb
end
end
def create
@user = User.new(params[:user])
@user.advancement = Advancement.new
@user.advancement.rank = Rank.new
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
else
format.html { render action: "new" }
end
end
end
end
在控制台中,我可以创建像我期望的那样工作的关系。当我尝试通过浏览器执行此操作时,我的所有对象都被实例化,外键是正确的,但如果我尝试查找 user.advancement,则会收到方法丢失错误。我是在使用 new 还是 create 错误,如果是,我该怎么办?对不起代码量,但我不知道任何其他方式来解释它。