从表单中保存两个模型不起作用 ruby radrails
我是 rad 导轨的新手。我想从一种形式同时写入两个表。
我有一个表 machine (以 nom 和 role 作为列)和一个表 ipvfour (以 machine_id 和 ip 作为列)。
所以我在模型中创建了“拥有并属于许多”的关系。
但是,当我尝试添加新机器时,如果因
未知属性而失败:ip
我真的不明白为什么,有人可以帮助我吗?
machine.controllers:
def 创建 @machine = Machine.new(params[:machine])
ipvfour = @machine.ip.create(params[:ip])
respond_to do |format|
if @machine.save && ipvfour.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 =>; “新” }
format.xml { 渲染:xml => @machine.errors,:状态=> :unprocessable_entity }
end
end
end
new.html.erb (机器)
新机器
'form', :locals => { :f_machine => f_machine } %>_form.html.erb(机器)
<% f_machine.fields_for :ip do |f_ip| %> <%= 渲染:部分 => 'ipvfours/form', :locals =>; { :f_ip => f_ip } %>
<% end %>
_form.html.erb (ipvfours)
<%= f_ip.label :ip %>
<%= f_ip.text_field :ip %>
添加机器的页面正确显示了所有字段,但似乎写入数据库失败,因为......我希望有人会你能帮助我吗?
提前致谢。
I'm a newbie with rad rails. I wanted to write at same time in two table from one form.
I have a table machine (with nom and role as column) and a table ipvfour (with machine_id and ip as column).
So I created in models the relation has-and-belongs-to-many.
But when I'm trying to add a new machine if failed with
unknown attribute: ip
I don't really understand why, can someone help me please ?
machine.controllers:
def create
@machine = Machine.new(params[:machine])
ipvfour = @machine.ip.create(params[:ip])
respond_to do |format|
if @machine.save && ipvfour.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
end
new.html.erb (machine)
New machine
'form', :locals => { :f_machine => f_machine } %>
_form.html.erb (machine)
<% f_machine.fields_for :ip do |f_ip| %>
<%= render :partial => 'ipvfours/form', :locals => { :f_ip => f_ip } %>
<% end %>
_form.html.erb (ipvfours)
<%= f_ip.label :ip %><br />
<%= f_ip.text_field :ip %>
The page to add a machine is correclty displayed with all fields but it seems that write in db failed due to .... I hope that someone will be able ti help me.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑:
如果需要,您可以在任何控制器中编辑任何模型。有一种魔术叫做
Accepts_nested_attributes_for(谷歌搜索!)
您的代码应如下所示:
在您的控制器中:
在您的视图中:
new.html.erb
_form.html.erb(机器)
_form.html.erb (ipvfours)
在您的模型中:
机器模型
最好的问候
simon
EDIT:
You can edit any model in any controller if you want. There's a magic trick called
accepts_nested_attributes_for (google it!)
Your code should look like:
In your Controller:
In your view:
new.html.erb
_form.html.erb (machine)
_form.html.erb (ipvfours)
In your Model:
Machine model
best regards
simon