No method error with form_for()

2019-08-21 20:01发布

Having some issues setting up a form for my worker active record. I have a user has_many workers relationship and had nested routes for the workers. my form code is below in my new.html.erb file in the workers directory of the view.

 <h1>Setup a Worker</h1>
  <p>
   Enter in the information below to connect your worker to our service.
  </p>
  <div class="row">
   <div class="span6 offset3">
    <%= form_for(@worker) do |w| %>

        <%= w.label :name %>
        <%= w.text_field :name %>

        <%=w.label :ip_address, "Ip address of the worker" %>
        <%=w.text_field :ip_address %>

        <%= w.submit "Create Worker", class: "btn btn-medium btn-primary" %>
    <% end %>
  </div>
</div>

In my workers controller I have this

class WorkersController < ApplicationController

  def new
    @worker = Worker.new
  end

  def show
  end

end

But when I try and load that Page I get this error

NoMethodError in Workers#new

and it points to this line

<%= form_for(@worker) do |w| %>

Thanks for the help.

2条回答
Viruses.
2楼-- · 2019-08-21 20:38
<%= form_for[@user, @worker] do |w| %>

    <%= w.label :name %>
    <%= w.text_field :name %>

    <%=w.label :ip_address, "Ip address of the worker" %>
    <%=w.text_field :ip_address %>

    <%= w.submit "Create Worker", class: "btn btn-medium btn-primary" %>
<% end %>

  def new
    @worker = Worker.new
    @user = User.find(params[:id])  or some other way to load the user
  end
查看更多
别忘想泡老子
3楼-- · 2019-08-21 21:00

as rmagnum said, you need to nest your form also, so rails can build the relation you established, when im working with forms i like to use a gem called simple_form, here you can check this railscasts: http://railscasts.com/episodes/234-simple-form, it sure helps allot with relations.

查看更多
登录 后发表回答