[英]date_select and build issue
我有一個下面的注冊模型,並嘗試在表單視圖中使用date_select和options_from_collection_for_select。 我在創建時遇到了麻煩,因為我不知道是否使用.build或.new,而date_select似乎正在分別以格式發送日/月/年,例如
Parameters: {"utf8"=>"✓", "authenticity_token"=>"HUQmbkmoATm6P/Avl11wmYqMrYeXVTZ/qmYfC2dpAFM=", "enrolment"=>{"course"=>"First Aid", "expiry(1i)"=>"2012", "expiry(2i)"=>"2", "expiry(3i)"=>"20"}, "commit"=>"Create Enrolment", "group_id"=>"2"}
我的注冊模型...
class Enrolment < ActiveRecord::Base
belongs_to :course
belongs_to :group
attr_accessible :course_id, :group_id, :expiry
validates_presence_of :expiry, :course_id, :group_id
end
在我的_form.html.erb中
<%= form_for([:admin,@group,@enrolment]) do |f| %>
---
<div class="field">
<%= f.label :course %><br />
<%= f.select :course, options_from_collection_for_select(@courses, 'name', 'name') %>
</div>
<div class="field">
<%= f.label :expiry %><br />
<%= f.date_select :expiry, :start_year => Time.now.year, :end_year => Time.now.year + 5 %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
在我的注冊控制器中
def new
@group = Group.find(params[:group_id])
#@enrolment = @group.enrolments.build
@enrolment = Enrolment.new
@courses = Course.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: @enrolment }
end
end
def create
@group = Group.find(params[:group_id])
@course = Course.find_by_name(params[:enrolment][:course])
@courses = Course.all
#@enrolment = Enrolment.new(params[:enrolment])
@enrolment = @group.enrolments.build(:course_id => @course.id)
respond_to do |format|
if @enrolment.save
format.html { redirect_to admin_group_path(@group), notice: 'Enrolment was successfully created.' }
format.json { render json: @enrolment, status: :created, location: @enrolment }
else
format.html { render action: "new" }
format.json { render json: @enrolment.errors, status: :unprocessable_entity }
end
end
end
當我嘗試提交其給我的驗證錯誤,提示我的有效期限不能為空時,如何將其添加到create方法中,使其有效? 任何幫助深表感謝
您是否嘗試過:
@enrolment = @group.enrolments.build(params[:enrolment])
基本上,您沒有使用用戶通過表單提交的信息,這就是您的有效期為零的原因。 當然 , 您必須對表格進行一些更改,例如 :
options_from_collection_for_select(@courses, 'id', 'name')
因此,您要傳遞ID而不是名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.