我正在尝试在db中写入另一个表中的id我有一个属于所有者表的机器表。
型号:
class Machine < ActiveRecord::Base
has_many :ipvfours, :dependent => :destroy
belongs_to :owners
accepts_nested_attributes_for :ipvfours
#accepts_nested_attributes_for :owners
# some check on fields
validates_uniqueness_of :nom, :scope => :nom
validates_length_of :nom, :within => 3..24
#validates_length_of :role, :within => 3..15
# return the value
def to_s
"#{nom},#{role}"
end
class Owner < ActiveRecord::Base
has_many :machines
#accepts_nested_attributes_for :machines
def name_owner
"#{name}"
end
end
表格中的_form信息中的已正确显示,但我在创建期间出错:
_form
<p>
<%= f_owner.label :owner %><br />
<%= f_owner.collection_select :owner_id, Owner.find(:all), :id, :name, :prompt => "Select an owner"%>
</p>
我的创建控制器:
def create
@machine = Machine.new(params[:machine])
respond_to do |format|
if @machine.save
flash[:notice] = 'Machine was successfully created.'
format.html { redirect_to(@machine) }
format.xml { render :xml => @machine, :status => :created, :location => @machine }
else
format.html { render :action => "new" }
format.xml { render :xml => @machine.errors, :status => :unprocessable_entity }
end
end
端
我有错误:
NameError in MachinesController#create
uninitialized constant Machine::Owners
并且请求是:
{"machine"=>{"nom"=>"fgj",
"owners"=>{"owner_id"=>"1"},
"role"=>"fgj",
"ipvfours_attributes"=>{"0"=>{"ip"=>"fgj"}}},
"commit"=>"Create",
"authenticity_token"=>"/j6/yo0KedbArk5Rj0SKGwIvg39+IMzmO78l/Fa7lHY="}
虽然我认为它应该是这样的:
{"machine"=>{"nom"=>"fgj",
"owner_id"=>{"owners"=>"1"},
"role"=>"fgj",
"ipvfours_attributes"=>{"0"=>{"ip"=>"fgj"}}},
"commit"=>"Create",
"authenticity_token"=>"/j6/yo0KedbArk5Rj0SKGwIvg39+IMzmO78l/Fa7lHY="}
但我经过了很多尝试后才知道。 提前谢谢。
答案 0 :(得分:0)
您的belongs_to
关联指的是复数owners
,应该是owner
单数。一台机器只能属于一个所有者。
belongs_to :owner