未定义的方法`email&#39;对于#<userinfo:0xc0ac77c>

时间:2015-06-16 05:23:14

标签: ruby-on-rails ruby activerecord

我在rails中有这个问题.. 它说undefined method email for #<UserInfo:0xc0ac77c> 我调试了几次,我无法追踪错误。

这是我的示例代码。

user_infos_controller.erb

class UserInfosController < ApplicationController
  before_action :check_user_profile, only: :index

  def index
    @user = User.find(current_user.id)
    puts @user
  end

  def new
    @user_info = current_user.build_user_info

  end

  def show
    @user = User.find(current_user)
  end

  def create

    @user_info = UserInfo.create(
      user_id: current_user.id,
      fname: params[:user_info][:fname],
      lname: params[:user_info][:lname],
      bday: params[:user_info][:bday],
      address: params[:user_info][:address],
      picture: params[:user_info][:picture])


    #if @user_info.save
      #redirect_to user_infos
    #else
      #render new_user_info_path
    #end
  end

  private
  def profile_params
    params.require(:user_info).permit(:fname, :lname, :bday, :address, :picture)
  end

  private

   def check_user_profile
    user = User.find(current_user)

    if !user.user_info
      redirect_to new_user_info_path
    end

  end
end

new.html.erb

<%= simple_form_for @user_info, html: { multipart: true } do |f| %>
        <% if @user_info.errors.any? %>
           <h2><%= pluralize(@user_info.errors.count, "error") %> Prevented this User from saving </h2>
            <ul>
            <% @user_info.errors.full_messages.each do |mg| %>
             <li><%= msg %></li>
             <% end %>
             </ul>
         <% end %>

          <div class="form-group">
          <%= f.input :picture, input_html: { class: "form-control"} %>
          </div>

          <div class="form-group">
          <%= f.input :fname, input_html: { class: "form-control"} %>
          </div>

          <div class="form-group">
          <%= f.input :lname, input_html: { class: "form-control"} %>
          </div>

          <div class="form-group">
          <%= f.input :address, input_html: { class: "form-control"} %>
          </div>

          <div class="form-group">
          <%= f.date_field :bday, input_html: { class: "form-control"} %>
          </div>

          <div class="form-group">
          <button class="btn btn-primary pull-right" type="submit">Save</button>
          </div>
<% end %>

这是针对用户数据库的

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

这适用于user_infos数据库

class CreateUserInfos < ActiveRecord::Migration
  def change
    create_table :user_infos do |t|
      t.string :fname
      t.string :lname
      t.date :bday
      t.string :address

      t.timestamps null: false
    end
  end
end



class AddAttachmentPictureToUserInfos < ActiveRecord::Migration
  def self.up
    change_table :user_infos do |t|
      t.attachment :picture
    end
  end

  def self.down
    remove_attachment :user_infos, :picture
  end
end

rails console

    Started POST "/user_infos" for 127.0.0.1 at 2015-06-16 13:44:14 +0800
Processing by UserInfosController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ig6pSrP9EV7ivQ3DRG/XPcwSQmr8oRhX+4YUtuxxqn/71ViwodxX06IMaQrzEQOWvOEjohAB1suFhubz0+cAJw==", "user_info"=>{"fname"=>"das", "lname"=>"dasa", "address"=>"dsasd", "bday"=>"2015-06-16"}}
  User Load (1.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 3]]
   (0.2ms)  BEGIN
   (2.8ms)  ROLLBACK
Completed 500 Internal Server Error in 148ms (ActiveRecord: 14.0ms)

NoMethodError (undefined method `email' for #<UserInfo:0xbcaa624>):
  app/controllers/user_infos_controller.rb:19:in `create'


  Rendered /home/allanprog/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (20.2ms)
  Rendered /home/allanprog/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (11.9ms)
  Rendered /home/allanprog/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (3.8ms)
  Rendered /home/allanprog/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (108.5ms)
Cannot render console with content type multipart/form-dataAllowed content types: [#<Mime::Type:0xa39d5f0 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html">, #<Mime::Type:0xa39d474 @synonyms=[], @symbol=:text, @string="text/plain">, #<Mime::Type:0xa38b65c @synonyms=[], @symbol=:url_encoded_form, @string="application/x-www-form-urlencoded">]

用户模型

    class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :pins
  has_one :user_info

end

user_info模型

class UserInfo < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  belongs_to :user

  has_attached_file :picture, styles: { medium: "300x300>" }
  validates_attachment_content_type :picture, :content_type => /\Aimage\/.*\Z/

end

2 个答案:

答案 0 :(得分:1)

模型中的Devise方法接受一些选项来配置其模块。

因此,如果您在User模型上使用设计,那么您必须从UserInfo模型中删除Devise方法,该模型位于

之下

从UserInfo

中删除它
devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable

要为多个模型配置Devise,请查看以下文档链接   https://github.com/plataformatec/devise

希望这会有所帮助。

答案 1 :(得分:0)

我认为没有任何理由导致NoMethodError (undefined method 'email' for #<UserInfo:0xbcaa624>)错误,但我可以看到的一个问题是:

create的{​​{1}}方法,您写过:

UserInfosController

但在@user_info = UserInfo.create( user_id: current_user.id, fname: params[:user_info][:fname], lname: params[:user_info][:lname], bday: params[:user_info][:bday], address: params[:user_info][:address], picture: params[:user_info][:picture]) 表中您尚未添加user_infos列。您应该通过以下迁移将user_id列添加到user_id表:

user_infos