0

私はラッドレールの初心者です。1つのフォームから2つの表に同時に書きたかったのです。

テーブル machine (nom と role を列として) とテーブル ipvfour (machine_id と ip を列として) があります。

そこで私はモデルの中で has-and-belongs-to many という関係を作りました。

しかし、失敗した場合に新しいマシンを追加しようとすると

不明な属性: ip

理由がよくわかりません。誰か助けてください。


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 }

そうしないと

format.html { render :action => "new" }

format.xml { render :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| %> <%= render :partial => 'ipvfours/form', :locals => { :f_ip => f_ip } %>

<% end %>


_form.html.erb (ipvfours)

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


マシンを追加するページはすべてのフィールドで正しく表示されますが、... が原因で db への書き込みに失敗したようです。誰かが私を助けてくれることを願っています。

前もって感謝します。

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

あなたの見解では:

new.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 に答える