ruby Rails new.html.erb没有接收值或没有将值传递给controller.from以获取新值,以下是我的new.html.erb

lh80um4z  于 2022-12-29  发布在  Ruby
关注(0)|答案(2)|浏览(123)

Rails new.html.erb未接收值或未将值传递给控制器。from以获取新值。
下面是我的新. html. erb

def new
  @departmentdetail=DepartmentDetail.new
end

def create
  @departmentdetail=DepartmentDetail.new(department_param)
  if @departmentdetail.save
    redirect_to ('index')
  else
    redirect_to('new')
  end
end

def department_param
  params.require(:departmentdetail).permit(:departmentname, :departmentemail, :password)
end
<%= form_for(@departmentdetail) do |f| %> 
  <table summary="Subject for fields"> 
    <tr> 
      <th> <%= f.label :departmentname %><br></th> 
      <td><%= f.text_field :departmentname %></td> 
    </tr> 
    <tr> 
      <th> <%= f.label :departmentemail %><br></th> 
      <td><%= f.text_field :departmentemail %></td> 
    </tr> 
    <tr> 
      <th> <%= f.label :password %><br></th> 
      <td><%= f.text_field :password %></td> 
    </tr>
  </table> 
  <%= f.submit("Create Department")%>
6ojccjat

6ojccjat1#

您没有完全遵循Ruby on Rails的命名约定。当存在名为DepartmentDetail的类时,强参数中的变量和键应该用下划线命名,如department_detail。此外,如果在保存时出现错误,重定向到new而不是只呈现new,将导致丢失当前状态:
我建议将您的控制器更改为:

def new
  @department_detail = DepartmentDetail.new
end

def create
  @department_detail = DepartmentDetail.new(department_detail_params)
  
  if @department_detail.save
    redirect_to :index
  else
    render :new
  end
end

def department_detail_params
  params.require(:department_detail).permit(:departmentname, :departmentemail, :password)
end

以及您对以下方面的看法:

<%= form_for(@department_detail) do |f| %> 
  <table summary="Subject for fields"> 
    <tr> 
      <th> <%= f.label :departmentname %><br></th> 
      <td><%= f.text_field :departmentname %></td> 
    </tr> 
    <tr> 
      <th> <%= f.label :departmentemail %><br></th> 
      <td><%= f.text_field :departmentemail %></td> 
    </tr> 
    <tr> 
      <th> <%= f.label :password %><br></th> 
      <td><%= f.text_field :password %></td> 
    </tr>
  </table> 
  <%= f.submit("Create Department")%>
<% end %>
pftdvrlh

pftdvrlh2#

当用户提交您要呈现的无效表单时-而不是重定向。

def create
  @departmentdetail = DepartmentDetail.new(department_param)
  if @departmentdetail.save
    redirect_to action: :index
  else
    render :new
  end
end

这将呈现new.html.erb视图,以便用户取回表单,但带有关于验证错误的消息。
在技术层面上,你实际上是在向用户发送非幂等请求时呈现一个响应--这是一个为该请求定制的响应。这与幂等的新操作非常不同(每个人的表单看起来都一样)。
如果您重定向用户,您将丢失所有用户输入和验证消息。

相关问题