我有一个嵌套资源的表单的简单场景,该表单可以正常工作,而不是在验证失败时表单呈现为空字段。我希望使用用户输入的值重新填充字段。
控制器
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
如果您的控制器是Discussion
控制器,请尝试添加以permit
部门的参数。
也许您可以在控制台上看到一些消息,例如Unpermitted parameters: var1 , var2
基本上是这样的:
def discussion_params
params.require(:discussion).permit(:title, :content , departments_attributes: [ :var1, :var2 ])
end