表格不更新数据库sinatra

时间:2018-02-19 12:18:39

标签: ruby sinatra

当我尝试使用Sinatra更新记录时,我遇到了表单与数据库连接的问题。

我在视图中创建了一个路径和一个表单。 首先,表单连接到get路由并带来相关数据。但是,当我修改字段并按提交按钮更新数据库时,记录不会更新。

get'/users/:id/edit'do
   # see the User we want to edit 
   @user = User.find_by_id(params[:id])
   #Assign the values to all properties
   @user.username = @user.username
   @user.password = @user.password
   @user.description =@user.description
   @user.city = @user.city
   @user.save
   erb:edit
 end

 put 'users/:id/edit' do
    @user = User.find_by_id(params[:id])
    #Assign the values to all properties
    @user.username = @user.username
    @user.password = @user.password
    @user.description =@user.description
    @user.city = @user.city
    @user.save
 end 

我的表单如下:

<form action="users/:id/edit" method="post" id="edit">
<input type="hidden" name="_method" value="put">
    User ID : :<%=@user.id%> <br>
    Username:<input type="text" name="username" value=
    <%=@user.username%>"><br>
    Password:<input type="password" name="password" value="
    <%=@user.password%>"><br>
   City:<input type="text" name="city" value="<%=@user.city%>">
     <br>
   Tell us more about you:<input type="text" name="description" 
     value="<%=@user.description%>"><br>
  <input type="submit" name="Update" class="btn btn-primary " >
</form>

你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

表单将记录ID传递给路径,因此我将表单修改为:

<form action="/users/edit/<%=@user.id%>" method="post" 
      id="edit">

和路线:

put '/users/edit/:id' do
  @user = User.find_by_id(params[:id])
  @user.city= params[:city]
  # rest of the fields need to be modified
end