如何创建一个ActiveRecord对象,当你设置一个属性? [英] How do you set an attribute when creating an ActiveRecord object?

查看:193
本文介绍了如何创建一个ActiveRecord对象,当你设置一个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,我创建一个对象上设置的属性。我觉得这应该工作:

I am trying to set an attribute on an object that I am creating. I feel like this should work:

 def create
    @album = Album.new(params[:album])
    @album.user = current_user

    if @album.save
       flash[:notice] = 'Album was successfully created for ' + current_user.login + '.'
       redirect_to albums_url 
    else
       render :action => "new"
    end
  end

但似乎忽略了分配到用户字段。任何想法?

推荐答案

假设你的模型关系设置正确*,这是更好地做:

Assuming that your model relationships are set up correctly*, it's better to do:

@album = current_user.albums.build(params[:album])

—这将正确填充 USER_ID 字段为新专辑到当前用户的ID

—This will correctly populate the user_id field for the new album to the ID of the current user.


*是这样的:

class User < ActiveRecord::Base
  has_many :albums
  .
  .
  .
end

class Album < ActiveRecord::Base
  belongs_to :user
  .
  .
  .
end

这篇关于如何创建一个ActiveRecord对象,当你设置一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆