我收到此错误:
我尝试跟随http://guides.rubyonrails.org/form_helpers.html#nested-forms,因为它与我正在尝试创建的内容非常接近
控制器:
class UsersController < ApplicationController
def new
@user = User.new
@user.contact_requests.build
end
def create
@user = User.new(user_params)
end
private
def user_params
# strong_parameters, which requires us to tell Rails exactly which parameters
# we want to accept in our controllers
params.require(:users).permit(:first_name, :last_name, :email, :phone_number, contact_requests_attributes: [:message])
# params.require(:users).permit!
end
end
模型:
class User < ActiveRecord::Base
# before_save { |user| user.email = user.email.downcase }
has_many :contact_requests
# validate the presence of the attributes
validates(:first_name, presence: true)
validates(:last_name, presence: true)
validates(:email, presence: true)
accepts_nested_attributes_for :contact_requests
end
class ContactRequest < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
validates :message, presence: true, length: { maximum: 500 }
end
形式:
<section id="contact">
<div class="container">
<div class="title-container">Contact Us</div>
<div class="title-caption">Reach us at (415)-911-9999</div>
<%= form_for(@user, remote: true, id: "contact-form", class: "contact-input") do |f| %>
<div class="col-md-12">
<div class="col-md-6">
<div class="contact-input-margin form-group">
<%= f.text_field(:first_name, class: "form-control", placeholder: "First name")%>
</div>
<div class="contact-input-margin form-group">
<%= f.text_field(:last_name, class: "form-control", placeholder: "Last name") %>
</div>
<div class="contact-input-margin form-group">
<%= f.email_field(:email, class: "form-control", placeholder: "Email") %>
</div>
<div class="contact-input-margin form-group">
<%= f.telephone_field(:phone_number, class: "form-control", placeholder: "Phone number") %>
</div>
</div>
<div class="contact-input-margin col-md-6">
<div class="form-group">
<%= f.fields_for :contact_requests do |builder| %>
<%= builder.text_area(:message, class: "form-control contact-margin", rows: "8", placeholder: "Message...") %>
<% end %>
</div>
</div>
</div>
<%= f.submit(class: "btn btn-xl") %>
<% end %>
</div>
</section>