我有一个@users 的编辑表单。在那里我有一个 text_field :username
<%= form_for @user, :url => { :action => "update" } do |f| %>
<%= render 'shared/error_messages', :target => f.object %>
<div class="field">
<%= f.label :username %><br />
<%= f.text_field :username %>
</div>
在我的用户模型中,我使用了friendly_id gem,也设置为:username。所以我的网址看起来像 domain.com/users/:username 而不是 :id。
has_friendly_id :username
现在在我的应用程序布局中,我还在导航中使用@user.username 链接到配置文件。
一切正常,除非我在保存时将 :username 字段留空。它无法保存验证的原因,
validates :username, :presence => true, :uniqueness => { :case_sensitive => false }, :length => { :maximum => 50 }
并尝试再次渲染“编辑”。但是要呈现“编辑”,我们需要用户名来在导航栏中创建链接。显然它是作为用户名=>“”传递的,即使它正确地未能保存并且正确的验证已经到位。
def update
@user = current_user
if @user.update_attributes(params[:user])
flash[:success] = "Account updated."
redirect_to :back
else
@title = "Edit"
render "edit"
end
结尾
所以我最终得到了一个 RoutingError:
No route matches {:action=>"show", :controller=>"users", :id=>#<User id: 6, username: "", persistence_token: "c2f2545659c186131537155347f46f7da5eb0d51b27707e71da...", created_at: "2011-03-14 14:26:48", updated_at: "2011-03-15 01:54:33", email: "test@test.com", crypted_password: "0d6489b1447d278bc4f7c86bab13787f226a10a302b43ec02ff...", password_salt: "Lq2G80iSVeaitB5PDwf", perishable_token: "Tm7Jzyq8QutfaxL3JLZ8", active: true>}