Kieran Andrews
Kieran Andrews

Reputation: 5885

Form for related model not showing up

I am trying to have a form show up for a related model, but it is not displaying when I view the page in a browser. How do I url field in my fields_for to display?

Here is my code:

User Model:

class UsersController < ApplicationController
  def new
    @user = User.new
    @user.websites.build
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      redirect_to root_url, :notice => "Signed up!"
    else
      render "new"
    end
  end
end

Website Model:

class Website < ActiveRecord::Base
  belongs_to :user
end

Users View:

<h1>Sign Up</h1>

<%= form_for @user do |f| %>
    <% if @user.errors.any? %>
...
    <% end %>
    <p>
      <%= f.label :email %><br/>
      <%= f.text_field :email %>
    </p>
    <p>
      <%= f.label :password %><br/>
      <%= f.password_field :password %>
    </p>
    <p>
      <%= f.label :password_confirmation %><br/>
      <%= f.password_field :password_confirmation %>
    </p>
    <% f.fields_for :websites do |builder| %>
        <%= builder.label :url %><br/>
        <%= builder.text_field :url %>
    <% end %>

    <p class="button"><%= f.submit %></p>
<% end %>

Final output:

finaloutput

Upvotes: 0

Views: 65

Answers (1)

noodl
noodl

Reputation: 17378

You missed the equals sign in your erb tag.

<% f.fields_for :websites do |builder| %>

.. should be ..

<%= f.fields_for :websites do |builder| %>

Does that fix it?

It looks like you're maybe confusing singular and plural in your fields_for as well. Calling it with the plural websites then treating the block as a singular website doesn't make sense.

Upvotes: 2

Related Questions