0
我有一個嵌套資源工作正常的表單,但驗證失敗時表單呈現爲空字段的情況很簡單。我希望用用戶輸入的值重新填充字段。驗證失敗後缺少嵌套的資源表單值
控制器
def new
@department = Department.find(params["department_id"])
end
def create
@department = Department.find(params["department_id"])
@discussion = @department.discussions.new(discussion_params)
@discussion.user_id = current_user.id
if @discussion.save
redirect_to department_discussions_path(@department)
else
render 'new'
end
end
private
def discussion_params
params.require(:discussion).permit(:title, :content)
end
表
<%= form_for([@department, @department.discussions.build]) do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title, class: "form-control" %>
</p>
<p>
<%= f.label :content %><br>
<%= f.text_area :content, class: "form-control", rows: 5 %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
模型
class Discussion < ApplicationRecord
belongs_to :user
belongs_to :department
validates :title, presence: true,
length: { minimum: 5, maximum: 25 }
end
路線ŝ
resources :departments do
resources :discussions
end