Rails:“状态”没有正确插入params?

时间:2012-10-11 19:48:19

标签: ruby-on-rails

您好我目前收到表单提交错误。我的应用程序基本上是一个用户,相册,图片(图片上传)。但是,当我尝试创建新专辑时,它给了我错误:

AlbumsController#show中的ActiveRecord :: RecordNotFound

找不到ID为123的专辑[WHERE“album_users”。“user_id”= 29 AND(status ='accepted')]

问题在于每张专辑可以有多个所有者,因此在创建专辑的表单中有一个复选框部分,您可以在其中突出显示您的朋友姓名并“邀请他们”成为所有者。这就是为什么我的创建函数看起来有点奇怪。这里的问题是得到:status => '接受'正常插入。请帮忙!

专辑控制器

def create
  @user = User.find(params[:user_id])
  @album = @user.albums.build(params[:album], :status => 'accepted')
  @friends = @user.friends.find(params[:album][:user_ids])
  for friend in @friends
    params[:album1] = {:user_id => friend.id, :album_id => @album.id, :status => 'pending'}
    AlbumUser.create(params[:album1])
  end
      #the next line is where the error occurs. why???
  if @user.save
    redirect_to user_album_path(@user, @album), notice: 'Album was successfully created.'
  else
    render action: "new"
  end
end


def show
  @user = User.find(params[:user_id])
  @album = @user.albums.find(params[:id]) #error occurs on this line
end

用户模型:

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, :conditions => "status = 'accepted'"
has_many :pending_albums, :through => :album_users, :source => :album, :conditions => "status = 'pending'"
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)

该行:

@album = @user.albums.build(params[:album], :status => 'accepted')

没有任何意义。只会尊重params[:album]。使用Hash#merge来组合:statusparams[:album](不修改最后一个):

@album = @user.albums.build(params[:album].merge(:status => 'accepted'))

<强>小心!

您已在albums协会指定条件:

has_many :albums, :through => :album_users, :conditions => "status = 'accepted'"

但是在制作相关专辑(如@user.album.build)时不会考虑它。您必须将其指定为,如哈希

has_many :albums, :through => :album_users, :conditions => {status: 'accepted'}

受到尊重。这样,您就无需在:status次来电中通过build:status的值将自动设置为'accepted'