验证失败后缺少嵌套资源表单值

时间:2017-05-25 11:19:03

标签: ruby-on-rails forms

我有一个简单的嵌套资源表单方案,除了验证失败之外,它可以正常工作,表单用空字段呈现。我希望用用户输入的值重新填充字段。

控制器

  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 

1 个答案:

答案 0 :(得分:0)

如果您的控制器是Discussion控制器,请尝试添加permit部门的参数。

也许您可以在控制台中看到Unpermitted parameters: var1 , var2

等消息

基本上是这样的:

def discussion_params
    params.require(:discussion).permit(:title, :content , departments_attributes: [ :var1, :var2 ])
end