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

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

AlbumsController#show中的ActiveRecord :: RecordNotFound

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

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

专辑控制器

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  :create validates_format_of :name, :with => /[A-Za-z]+/, :on => :create validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[az]{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 

结束

这条线:

 @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 。 值:status将自动设置为'accepted'