0

我有一个对我来说似乎很简单的问题,但我无法找出解决方案。因此,如果您能提供任何帮助,我将不胜感激:-)

首先,我使用 Devise gem 来创建我的用户。

这是app/models/user.rb

class User < ActiveRecord::Base
  before_save :default_values
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :avatar, :address, :longitude, :latitude

  has_many :products, dependent: :destroy

  has_attached_file :avatar, styles: { medium: "300x300>", thumb: "50x50>" },
                         url: "users/:id/:style/:basename.:extension",
                         path: ":rails_root/public/assets/users/:id/:style/:basename.:extension",
                         default_url: "users/missing/:style/missing.png"


  #Geokit
  geocoded_by :address
  after_validation :geocode, if: :address_changed?

  def default_values
    self.address ||= "Paris"
    self.geocode
  end

end

我为我的静态页面创建了一个 Home 控制器,我的 root_path 是app/views/home/index.html.erb,我们可以在其中找到:

<%= render 'new_name' %>

我们来看看这个app/views/home/_new_name.html.erb

<!-- Button to trigger modal -->
<a href="#yourName" role="button" class="btn" data-toggle="modal">OK</a>

 <!-- Modal -->
<div id="yourName" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel"><%= t('home.your_name') %></h3>
  </div>
  <div class="modal-body">
    <%= form_for(@current_user) do |f| %>
      <p>
        <%= f.label :name, t('name'), placeholder: t('home.your_name') %>
        <%= f.text_field :name %>
      </p>
      <p>
        <%= f.submit t('update'), class: "btn"%>
      </p>
     <% end %>
  </div>
</div>

是的,我确实使用了 bootsrap 的魔法 ;-)

作为记录,我的config/routes.rb

Dindon::Application.routes.draw do
  root to: "home#index"

  resources :products

  devise_for :users
  match 'users/:id' => 'users#show', :as => :user
  match 'users' => 'users#index'
end

所以,最后要做的就是配置我的 HomeController 给我的实例变量 @current_user 他的新名字。这是我的app/controllers/home_controller.rb

class HomeController < ApplicationController
  def index
    @current_user = User.find_by_id(current_user.id)
  end

  def update
    @current_user.update_attributes(params[:user])
  end
end

但它根本不起作用。当我单击确定按钮时,我有一个窗口,我填写字段,单击提交按钮,它会将我发送到用户显示视图,但不考虑更改名称。

你知道我做错了什么吗?

4

1 回答 1

0

看起来您没有在更新方法中定义 @current_user 。

您还使用 form_for(@user) 而您尝试在更新方法中获取 params[:user] ,这是不一致的。

在我看来,你应该在更新它之前定义@current_user(使用参数,就像你在索引中所做的那样),或者直接使用设计 *current_user* 方法(注意这里没有@,所以我们调用了设计方法,而不是实例变量)。

请注意,调用 *current_user* 将更新单击的登录用户,而使用 find 方法将允许您修改任何其他用户,只要在参数中提供了有效的 id。

于 2013-03-21T14:54:58.213 回答