2017-05-25 88 views
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 

回答

0

如果您的控制器是Discussion控制器,嘗試添加到permit系的參數。

也許你可以看到控制檯像Unpermitted parameters: var1 , var2

一些消息基本上是一些這樣的:

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