::的ActiveSupport HashWithIndifferentAccess

时间:2013-06-11 17:34:04

标签: ruby-on-rails ruby ruby-on-rails-3

我的控制器是这样的

class FriendController < ApplicationController
  def friend_list
    @user = User.new
  end

  def be_mine_friend
    @user = params[:user]
    if @user.save?
        redirect_to friend_mine_friend_url
        flash[:notice] = "#{@user[:name]} have been added to my friend list"
    else
        redirect_to friend_friend_list_path
    end     
  end

  def mine_friend
    @title = "Details list of Mine Friend"
    @friend = @user.paginate(page: params[:page], per_page: 10)
    respond_to do |format|
      format.html 
      format.json { render json: @friend }
    end
  end
end

查看friend_list的页面

    <div class="container">
        <%= notice %>
        <%#= errors %>
        <%= form_for(@user, url: friend_be_mine_frien_path) do |user| %>
            <%= user.text_field 'name', placeholder: "Your name Please" %></br>
            <%= user.text_field 'email', placeholder: "Your Email Please" %></br>
            <%= user.text_field 'address', placeholder: "Your Address Please" %></br>
            <%= user.submit "Be Mine Friend", class: "btn btn-primary" %>
        <% end %>
    </div>

view page for mine_friend

<div class="container">
    <p><strong><%= @title %></strong><p>
        <%= notice %>
    <%= will_paginate @friend, previous_label: "<<", next_label: ">>", class: "pagination pagination-large" %>
    <table class="table table table-striped">
        <tr>
            <th>Name</th>
            <th>Address</th>
            <th>Email</th>
        </tr>
        <% @friend.each do |friend| %>
        <tr>    
            <td><%= friend.name %></td>
            <td><%= friend.address %></td>
            <td><%= friend.email %></td>
        </tr>
        <% end %>   
    </table>
</div>

和模型是

class User < ActiveRecord::Base
  attr_accessible :address, :email, :message, :name

  validates :address, :email, :message, :name, presence: :true
end

当我尝试从friend_list保存用户时,我得到了这样的

Processing by FriendController#be_mine_friend as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"5A1dXtuYJpfqpOphkdl+WA657T3ok2zu/8U1v1B8tEg=", "user"=>{"name"=>"Amritdeep", "email"=>"amritdeepdhungana@hotmail.com", "address"=>"Bou"}, "commit"=>"Be Mine Friend"}
Completed 500 Internal Server Error in 1ms6090>:

错误是

NoMethodError - undefined method `save?' for #<ActiveSupport::HashWithIndifferentAccess:0x00000003c06090>:

我现在该怎么办?你们有什么解决方案吗?我不知道为什么会出现ActiveSupport::HashWithIndifferentAccess错误。你们对此有什么想法吗?

1 个答案:

答案 0 :(得分:5)

@user = params[:user]
if @user.save?

params [:user]是一个哈希值。它不是用户对象。这是常态:

@user = User.create(params[:user])