0

我是 rad rails 的新手。我想从一种形式同时写在两个表中。

我有一个表机器(以 nom 和 role 作为列)和一个表 ipvfour(以 machine_id 和 ip 作为列)。

因此,我在模型中创建了“has-and-belongs-to-many”关系。

但是当我尝试添加一台新机器时,如果失败了

未知属性:ip

我真的不明白为什么,有人可以帮助我吗?


机器控制器:

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 }

别的

format.html { 渲染 :action => "new" }

format.xml { 渲染 :xml => @machine.errors, :status => :unprocessable_entity }

结尾

结尾

结尾


new.html.erb(机器)

新机

'form', :locals => { :f_machine => f_machine } %>



_form.html.erb(机器)



<% f_machine.fields_for :ip do |f_ip| %> <%= 渲染 :partial => 'ipvfours/form', :locals => { :f_ip => f_ip } %>

<% end %>


_form.html.erb (ipvfours)

<%= f_ip.label :ip %><br /> <%= f_ip.text_field :ip %>


添加机器的页面正确显示所有字段,但似乎由于...而在数据库中写入失败。我希望有人能够帮助我。

提前致谢。

4

1 回答 1

0

编辑:

如果需要,您可以在任何控制器中编辑任何模型。有一个魔术叫 accept_nested_attributes_for (谷歌它!)

您的代码应如下所示:

在您的控制器中:

def new 
  # .... your code ....

  # create empty machine
  @machine  = Machine.new

  # add one empty ip 
  @machine.ipvfours.build

  # .... your code ....

end

def create 

  # fill machine and ipvfours directly 
  @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

end

在您看来:

新的.html.erb

<% form_for(@machine) do |f_machine| %>  

  <%= render :partial => 'form', :locals => { :f_machine => f_machine } %>

  <%= f_machine.submit 'Create' %>

<% end %>

<%= link_to 'Back', machines_path %>

_form.html.erb(机器)

<%= f_machine.error_messages %>

<% f_machine.fields_for :ipvfours 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 %>

在您的模型中:

机器型号

class Machine < ActiveRecord::Base

    has_many :ipvfours, :dependent => :destroy
    accepts_nested_attributes_for :ipvfours

end

此致

西蒙

于 2010-09-07T15:15:08.670 回答