2015-05-12 52 views
0

我在另一个视图中有一个用户表单,它非常适合创建用户。即使他们已经是用户,我也希望人们填写此表单。如果用户存在然后更新

如果他们已经是用户,我希望表单更新他们的位置,如果他们输入任何内容并保存。

用户表单

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> 
<%= devise_error_messages! %> 

<div class="form-group"> 
    <%= f.label :location, "Where are you based?" %><br /> 
    <%= f.text_field :location, placeholder: "E.g. London", class: "full-width form-field" %> 
</div> 

<div class="form-group"> 
    <%= f.label :email, "What is your email?" %> 
    <%= f.email_field :email, placeholder: "Enter email", class: "full -width form-field" %> 
</div> 

<div class="actions"> 
    <%= f.button "GO", class: "btn btn-1R btn-orange full-width", id: "submit_button" %> 
</div> 

<% end %> 

我想我可以做的模型before_validation方法来检查该用户是否存在,如果不创建一个。这是正确的吗?

before_validation :check_user, :on => :create 

def check_user 
    @user = User.where(email: self.email).first 
    unless @user.blank? 
     @user.update_attributes(:location => self.location) 
     @user.save 
    else 
     puts 'NEW USER' 
    end 
end 

这仍然抛出'电子邮件已被采取'的错误。

我该如何杀死'创建'方法,只是在这里引起更新方法?还是我这样做完全错了?

回答

0

我想你想避免在你的模型中创建记录。这似乎是你想要做的是结合注册#创建注册#更新。您可以通过在您的注册控制器中重写devise's registrations#create method来完成此操作。所以你可以做的是在构建新资源之前检查你的用户是否已经存在。事情是这样的......:

def create 
    if user = User.where(email: sign_up_params[:email]).first 
    user.update_attributes(location: sign_up_params[:location]) 
    self.resource = user 
    else 
    self.resource = resource_class.new_with_session(sign_up_params || {}, session) 
    end 

    resource.save 
    yield resource if block_given? 
    if resource.persisted? 
    if resource.active_for_authentication? 
     set_flash_message :notice, :signed_up if is_flashing_format? 
     sign_up(resource_name, resource) 
     respond_with resource, location: after_sign_up_path_for(resource) 
    else 
     set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format? 
     expire_data_after_sign_in! 
     respond_with resource, location: after_inactive_sign_up_path_for(resource) 
    end 
    else 
    clean_up_passwords resource 
    set_minimum_password_length 
    respond_with resource 
    end 
end 
+0

虽然这仍然不会运行设计标准验证吗?我也得到'未定义的方法'保存为真:TrueClass'运行这个。 – MikeHolford

+0

是的,它会。你会得到未定义的方法错误,因为上面应该是user.update/user.update_attributes /你想更新你的用户的方案,然后self.resource = user。我会更新代码 – Hannah

0

我设法通过该方法移动到控制器,并呼吁

before_action :check_user, only: [:create] 

def check_user 
    @user = User.where(email: sign_up_params[:email]).first 
    unless @user.blank? 
    @user.update_attributes(:location => sign_up_params[:location]) 
    @user.save 
    redirect_to(:back) and return 
    else 
    puts 'NEW USER' 
    end 
end 

redirect_to(:back) and return是什么钉它来解决这个问题。 :)

相关问题