2017-04-23 113 views
0

我有用户和配置文件模型。我为用户和个人资料创建了一个表单。当任何人输入详细信息时,只有用户的详细信息会保存在数据库中而不是配置文件中。在数据库中不保存信息的嵌套表格

用户模型

class User < ApplicationRecord has_many :comments 

    has_many :repositories 
    has_many :searches 
    has_many :issues 
    has_many :feedbacks 
    has_one :profile 
#-------------------------- VALIDATIONS-----------------------------------------# 
    EMAIL_REGEX = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i 
    validates :username, :presence => true, :uniqueness => true, :length => { :in => 3..20 } 
    validates :email, :presence => true, :uniqueness => true, :format => EMAIL_REGEX 
    validates :password, :confirmation => true #password_confirmation attr 
    validates_length_of :password, :in => 6..20, :on => :create 
#-------------------------- ENCRYPTION-----------------------------------------# 

    before_save :encrypt_password, :default_values 
    after_save :clear_password 

    def encrypt_password 
    if password.present? 
     self.salt = BCrypt::Engine.generate_salt 
     self.encrypted_password= BCrypt::Engine.hash_secret(password, salt) 
    end 
    end 

    def clear_password 
    self.password = nil 
    end 
#-------------------------- AUTHENTICATION-----------------------------------------# 
    def self.authenticate(username_or_email="", login_password="") 
    if EMAIL_REGEX.match(username_or_email) 
     user = User.find_by_email(username_or_email) 
    else 
     user = User.find_by_username(username_or_email) 
    end 
    if user && user.match_password(login_password) 
     return user 
    else 
     return false 
    end 
    end 

def match_password(login_password="") 
    encrypted_password == BCrypt::Engine.hash_secret(login_password, salt) 
end 

private 
def default_values 
    type ||= false 
end 

end 

剖面模型

class Profile < ApplicationRecord 

    before_save :default_values 
    belongs_to :user 


    validates :fname, :presence=> true 
    validates :lname, :presence=> true 
    validates :city, :presence=> true 
    validates :state, :presence=> true 
    validates :country, :presence=> true 
    validates :zip_code, :presence=> true 
    validates :phone_no, :presence=> true 

    private 
    def default_values 
    followers ||= 0 
    following ||= 0 
    end 
end 

用户控制器

class UsersController < ApplicationController 
    before_filter :save_login_state, :only => [:new, :create] 

    def new 
    @user = User.new 
    @profile = Profile.new 
    end 

    def create 
    @user = User.new(user_params) 
    @profile = Profile.new(profile_params) 
    if @user.save 
      @profile.save 
      flash.now[:notice] = "Signed up successfully !!" 
      @users = User.all        # to get all users in @users 
      @profiles = Profile.all       # to get profile of all users in @profiles 
      render "show"         # display show.html.erb while passing @users and @profiles ? 
     else 
      flash.now[:notice] = "Invalid form" 
      flash.now[:color] = "Invalid" 
      redirect_to :root 

     end 
    end 

def show 
    @users = User.all      # same as above. not working if removed from above. 
    @profiles = Profile.all    # same as above. not working if removed from above. 
end 

def edit 
    user = @current_user    
    profile = user.profile    
end 

private 
def user_params 
    params.require(:user).permit(:username, :email, :password) 
end 

def profile_params 
    params.require(:profile).permit(:fname, :lname, :dob, :city, :state, :country, :zip_code ,:phone_no) 
end 

end 

注册页面 - new.html.erb

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<link href="signup.css" rel='stylesheet' type='text/css' /> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> 
<!--webfonts--> 
<link href='http://fonts.googleapis.com/css?family=Oxygen:400,300,700' rel='stylesheet' type='text/css'> 
<!--//webfonts--> 
</head> 
<body id="signup_body"> 
    <ul id="navigation"> 
    <li><%= link_to "Home", {:action=>'index', :controller=>'home'}, class: "home_list"%></li> 
    <li><%= link_to "Personal", {:action=> 'login', :controller=>'sessions'}, class: "home_list"%></li> 
    <li><%= link_to "Business", {:action=>'business', :controller=> 'home'}, class: "home_list" %></li> 
    <li><%= link_to "Pricing", {:action=>'pricing', :controller=>'home'}, class: "home_list" %></li> 
    <li><%= link_to "Signup", {:action=>'new', :controller=>'users'}, class: "home_list" %></li> 
    </ul> 
<div class="main"> 
    <div class="social-icons"> 
     <div class="col_1_of_f span_1_of_f"> 
     </div> 
     <div class="col_1_of_f span_1_of_f"> 
     </div> 
     <div class="clear"> </div> 
     </div> 
     <h2>Signup</h2> 
      <div class="lable"> 
     <%= form_for @user, :as => :user, url:{action: :"create"} do |f| %> 
      <div class="col_1_of_2 span_1_of_2"><%= f.text_field :username, :class => 'text', :value=>'Username', :onfocus=>"this.value = '';" %></div> 
      <div class="col_1_of_2 span_1_of_2"><%= f.text_field :email, :class => 'text', :value=>'Email', :onfocus=>"this.value = '';" %></div> 
      <div class="col_1_of_2 span_1_of_2"><%= f.password_field :password, :class => 'text', :value=>'Password', :onfocus=>"this.value = '';" %></div> 
      <div class="col_1_of_2 span_1_of_2"><%= f.password_field :password_confirmation, :class => 'text', :value=>'Password', :onfocus=>"this.value = '';" %></div> 
       <div class="clear"> </div> 
      </div> 
      <div class="lable-2"> 
     <%= fields_for :profile, :as => :profile, url:{action: :"create"} do |t| %> 
      <b><u>Profile</b></u> 
      <%= t.text_field :fname, :class => 'text', :value=>'First Name', :onfocus=>"this.value = '';" %> 
       <%= t.text_field :lname, :class => 'text', :value=>'Last Name', :onfocus=>"this.value = '';" %> 
      <%= t.text_field :dob, :class => 'text', :value=>'Date of birth (yyyy/mm/dd)', :onfocus=>"this.value = '';" %> 
         <%= t.text_field :city, :class => 'text', :value=>'City', :onfocus=>"this.value = '';" %> 
         <%= t.text_field :state, :class => 'text', :value=>'State', :onfocus=>"this.value = '';" %> 
         <%= t.text_field :country, :class => 'text', :value=>'Country', :onfocus=>"this.value = '';" %> 
         <%= t.text_field :zip_code, :class => 'text', :value=>'Zip Code', :onfocus=>"this.value = '';" %> 
         <%= t.text_field :phone_no, :class => 'text', :value=>'Phone Number', :onfocus=>"this.value = '';" %> 
      </div> 
      <h3>By creating an account, you agree to our <span> class="term">Terms & Conditions</span></h3> 
      <br> 
      <%= flash[:message] %> 
      <div class="submit"> 
       <%= f.submit(:Submit, :value=> 'Create Account' , :style=> 'margin-left:5px;float:left;margin-top:55px;height:50px;width:520px;padding:10px;border-radius:4px;') %> 
      </div> 
      <div class="clear"> </div> 
     </form><br><br> 
     <!--//end-main----> 
     </div> 
</body> 
<%end%> 
<% end %> 
</html> 

控制台

(0.1ms) begin transaction 
    User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE "users"."username" = ? LIMIT ? [["username", "qwerty"], ["LIMIT", 1]] 
    User Exists (0.2ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ? [["email", "[email protected]"], ["LIMIT", 1]] 
    SQL (0.5ms) INSERT INTO "users" ("username", "password", "email", "created_at", "updated_at", "salt", "encrypted_password") VALUES (?, ?, ?, ?, ?, ?, ?) [["username", "qwerty"], ["password", "1234567"], ["email", "[email protected]"], ["created_at", 2017-04-23 06:44:39 UTC], ["updated_at", 2017-04-23 06:44:39 UTC], ["salt", "$2a$10$bZSiXCku1iYArTRpo4ExAO"], ["encrypted_password", "$2a$10$bZSiXCku1iYArTRpo4ExAOXYGjLVKN.PJCMOUdoat0CrYIY/zUGM."]] 
(2.0ms) commit transaction 
    (0.2ms) begin transaction 
    (0.1ms) rollback transaction 
    Rendering users/show.html.erb within layouts/application 
    User Load (0.5ms) SELECT "users".* FROM "users" 
    Profile Load (0.3ms) SELECT "profiles".* FROM "profiles" 
    Rendered users/show.html.erb within layouts/application (4.0ms) 
Completed 200 OK in 144ms (Views: 37.0ms | ActiveRecord: 4.3ms) 

P.S:我是新来的轨道。

+0

你确定你有'user'和'profile'之间的连接吗?而不是'@profile = Profile.new(profile_params)'最好创建这样的配置文件:'@profile = user.build_profile',并在那里传递参数。 – TiSer

+0

你的意思是@ profile = user.build_profile(profile_params)? –

+0

是的,试试看。 – TiSer

回答

0

您可以使用一些更简单,对用户模型中加入这一行

accepts_nested_attributes_for :profile, reject_if: :all_blank, allow_destroy: true 

这个那么如果PARAMS有正确的结构,当你创建的用户,配置文件也会被添加。只记得在控制器上添加许可证的参数

高清user_params params.require(:用户).permit(:用户名,:电子邮件,:密码, profile_attributes:[:ID,:ATTRIBUTE1,: attribute2]) 结束

,并在您创建的动作,你只需要添加这个

def create 
    @user = User.new(user_params) 
    if @user.save    
      flash.now[:notice] = "Signed up successfully !!" 
      @users = User.all 
      @profiles = Profile.all  
      render "show" 
     else 
      flash.now[:notice] = "Invalid form" 
      flash.now[:color] = "Invalid" 
      redirect_to :root 

     end 
    end 

以这种方式,用户的配置文件将被创建,如果在其中任何一个错误,用验证,不会保存,并且您不必担心如果教授删除用户ile没有保存。