1

我第一次使用 STI 创建应用程序,但我偶然发现了一个令人费解的障碍。

给定以下两个具有继承的模型:

User.rb
class User < ActiveRecord::Base
attr_accessible :email, :first_name, :last_name, #more follows


Waiter.rb
class Waiter < User

我在 /waiters/users/[:id]/edit 上做了一个表格,它执行以下操作:

<%= simple_form_for @user, 
      :url => { :controller => "admin/waiters/users", :action => "update"} do |f| %>
 <%= f.input :first_name %>
 <%= f.input :last_name %>
 <%= f.input :email %>
 <%= f.input :start_date %>
 <%= f.button :submit, "Save", class: "btn btn-primary"%>
<% end %>

但是,按下提交是通过发布请求但无法更新实际数据。还是因为路线不对?请参阅下面的 SQL 转储:

Started PUT "/admin/waiters/users/6" for 127.0.0.1 at 2013-02-10 20:45:59 -0800
Processing by Admin::Waiters::UsersController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"6EB82/aWryLgj/tZcvoOWmw98PAPmJYUViAQronv6Fw=", "waiter"=>{"first_name"=>"John", "last_name"=>"Smith", "email"=>"john@foobaz.com"}, "commit"=>"Save", "id"=>"6"}
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  Role Load (0.5ms)  SELECT "roles".* FROM "roles" INNER JOIN "user_roles" ON "roles"."id" = "user_roles"."role_id" WHERE "user_roles"."user_id" = 1
  Waiter Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 6 LIMIT 1
   (0.1ms)  BEGIN
  User Exists (0.4ms)  SELECT 1 AS one FROM "users" WHERE ("users"."email" = 'john@foobaz.com' AND "users"."id" != 6) LIMIT 1
  CACHE (0.0ms)  SELECT 1 AS one FROM "users" WHERE ("users"."email" = 'john@foobaz.com' AND "users"."id" != 6) LIMIT 1
   (2.4ms)  UPDATE "users" SET "perishable_token" = 'FplOAv6d4eOBv0gHW3b', "updated_at" = '2013-02-11 04:45:59.206797' WHERE "users"."id" = 6
   (0.7ms)  COMMIT
Redirected to http://localhost:3000/admin/waiters/users

控制器似乎在更新操作后重定向得很好,但数据没有保存。我在这里想念什么?感谢对 Rails 初学者的帮助。

这是在 controllers/admin/waiters/ 中找到的用户控制器

 def edit
    form_info
    @user = Waiter.find(params[:id])
  end

  def update
    @user = Waiter.find_by_id(params[:id])
    if @user.update_attributes(params[:user])
      flash[:notice] = "Successfully assigned Waiter."
      redirect_to admin_waiters_users_url()
    else
      form_info
      render :action => 'edit'
    end
  end
4

1 回答 1

3

问题是您从 params 哈希中提取了错误的值。查看日志:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"6EB82/aWryLgj/tZcvoOWmw98PAPmJYUViAQronv6Fw=", "waiter"=>{"first_name"=>"John", "last_name"=>"Smith", "email"=>"john@foobaz.com"}, "commit"=>"Save", "id"=>"6"}

更新的属性通过waiter密钥进行散列。现在看看你的更新代码:

if @user.update_attributes(params[:user])

你得到params[:user]. 由于您使用的是 STI,我假设您想保留 params[:user],因此您需要更改服务员的表单代码。你应该做:

<%= simple_form_for @user, as: :user,
      :url => { :controller => "admin/waiters/users", :action => "update"} do |f| %>
于 2013-02-11T05:42:39.807 回答