Rails:未定义的方法'(MODELNAME)'?

时间:2012-10-10 20:13:34

标签: ruby-on-rails

您好我正在制作一个用于上传图片的网络应用。有用户,相册和照片。当我尝试编辑用户的个人资料信息时,我无法弄清楚发生了什么。它告诉我在UsersController#update中有一个未定义的方法'专辑'NoMethodError,但我甚至没有在#update动作中调用专辑。

def update
  respond_to do |format|
    if current_user.update_attributes(params[:user])
      format.html { redirect_to current_user, notice: 'User successfully updated.'}
      format.json { render json: current_user, status: :created, location: current_user }
    else
      format.html { render action: 'edit' }
      format.json { render json: current_user.errors, status: :unprocessable_entity }
    end
  end
end

错误特别出现在我的更新操作的第2行和第3行。这是错误:

app/controllers/users_controller.rb:45:in 'block in update'

app/controllers/users_controller.rb:44:in update'`

谁知道到底发生了什么事?

为用户编辑表单

<%= form_for(@user) do |f| %>

<div class="formhold">
<div class="field">
    <% if @user.profilepic? %>
    <%= image_tag @user.profilepic.url %>
    <% end %>

    <%= f.label :profilepic, "Profile Picture" %>
    <%= f.file_field :profilepic %>
</div>
<div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
</div>
<div class="field">
    <%= f.label :email %>
    <%= f.text_field :email %>
</div>

<div>
    <%= f.submit 'Submit', :class => 'submitbutton' %>
</div>



<% if @user.errors.any? %>
    <div id="error_exp">
        <h2><%= pluralize(@user.errors.count, "error") %> occurred.</h2>

        <ul>
        <% @user.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
        <% end %>
        </ul>
    </div>

    </div>
<% end %>
<% end %>



<%= link_to "Back", user_path(@user) %>

用户模型

class User < ActiveRecord::Base

has_secure_password
attr_accessible :email, :name, :password, :password_confirmation, :profilepic
validates_presence_of :password, :on => :create

validates_format_of :name, :with => /[A-Za-z]+/, :on => :create
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
validates_length_of :password, :minimum => 5, :on => :create
validates :album, :uniqueness => true

has_many :album_users
has_many :albums, :through => :album_users
accepts_nested_attributes_for :albums

has_many :friendships, :dependent => :destroy
has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at

has_attached_file :profilepic

before_save { |user| user.email = email.downcase }

def name_with_initial
  "#{name}"
end

private

  def create_remember_token
    self.remember_token = SecureRandom.urlsafe_base64
  end

1 个答案:

答案 0 :(得分:1)

尝试发表评论:

validates :album, :uniqueness => true

假设:相册是用户的属性/方法并且失败。您应该根据您的业务逻辑处理相册模型中相册的唯一验证。您可以根据user_id或其他具有:scope => [:user_id]

的属性对其进行验证