嵌套表单不保存数据库中的信息

时间:2017-04-23 07:13:23

标签: ruby-on-rails ruby-on-rails-4

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

用户模型

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", "qwerty@gmail.com"], ["LIMIT", 1]]
  SQL (0.5ms)  INSERT INTO "users" ("username", "password", "email", "created_at", "updated_at", "salt", "encrypted_password") VALUES (?, ?, ?, ?, ?, ?, ?)  [["username", "qwerty"], ["password", "1234567"], ["email", "qwerty@gmail.com"], ["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:我是铁杆新手。

1 个答案:

答案 0 :(得分:0)

您可以使用更简单的内容,在用户模型上添加此行

document.getElementById("datatable1").style.display = "block" //Show the table
document.getElementById("datatable2").style.display = "none";  //Hide the table

function handleClick(myRadio) {
if (myRadio.value == "table2"){
    document.getElementById("datatable1").style.display  = "none";
    document.getElementById("datatable2").style.display  = "block" ;
}
else{
    document.getElementById("datatable1").style.display  = "block" ;
    document.getElementById("datatable2").style.display  = "none";
}
}

然后如果params具有正确的结构,则在创建用户时,也会添加配置文件。只记得在控制器中添加许可证上的参数

def user_params   params.require(:user).permit(:username,:email,:password,   profile_attributes:[:id,:attribute1,:attribute2]) 端

在您的创建操作上,您只需添加此

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

以这种方式,将创建用户和个人资料,如果其中任何一个出现错误,使用验证,将不会保存任何内容,并且您不必担心删除用户该档案未被保存。