2

What is the proper way to have a form in a partial view reference an empty model in order to handle validation properly as defined on the model. Should I instantiate a new, empty model in the partial view and pass it through to the form? Here is what I'm working with...

MODEL

class NewsletterSignup < ActiveRecord::Base
  def self.columns()
    @columns ||= [];
  end

  def self.column(name, sql_type = nil, default = nil, null = false)
    columns << ActiveRecord::ConnectionAdapters::Column.new(name, default, sql_type, null)
  end

  def persisted?
    false
  end

  column :first_name, :string
  column :last_name, :string
  column :email, :string
  column :zip, :string

  validates :first_name, :last_name, :email, :zip, :presence => true
  validates :email, :format => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
  validates :zip, :format => /^\d{5}$/
end

Partial View

<%
    signup = newsletter_signup.new
%>

<%= simple_form_for(signup, ...) do |f| %>
    <%= f.input :first_name, :label => "First Name:" %> 
    <%= f.input :last_name, :label => "Last Name:" %>
    <%= f.input :email, :label => "Email:" %>
    <%= f.input :zip, :label => "Zip:" %>

    ...
<% end %>

But I can't seem to instantiate a new model like this. I assume I have to reference it in the view. (Note, I'm new to rails but have a decade+ of professional software development experience, so I apologize if some of rails constructs seem foreign to me and I may just be overlooking something simple!)

4

1 回答 1

0

如果您的控制器看起来像这样

def new
  Model.new
end

def create
  @model = Model.new(params[:model])

  if @model.save
    redirect root_path, notice: "Saved"
  else
    render action: 'new'
  end
end

def edit
  Model.find(params[:id])
end

def update
  if @model.update(params[:model])
    redirect root_path, notice: "Updated"
  else
    render action: 'edit'
  end
end

您可以拥有如下视图:

# new.html.erb
<%= render 'form' %>

# edit.html.erb
<%= render 'form' %>

# _form.html.erb
<%= form_for @model do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
  ...
<% end %>
于 2013-09-22T03:54:51.963 回答