将一个对象的属性设置为另一个对象的属性
Setting the attribute of an object to be and attribute of another object
我对 rails 上的 Ruby 很陌生。我正在尝试将产品对象 (:userid) 设置为用户对象 ID (user.id)。到目前为止我已经得到了这个
class Product < ActiveRecord::Base
before_create :set_userid
def set_userid
self.userid = User.new(params[:id])
end
end
在创建产品对象之前是否有其他方法设置值?
Consider using associations
使用像
这样的助手轻松定义模型之间的关系
Product
belongs_to :user
User
has_many :products
您的代码将无法运行,因为模型无法访问 params
。因此,您应该在控制器的操作中分配用户实例:
def your_action
...
product = ...
product.user = User.new(params[:id])
我对 rails 上的 Ruby 很陌生。我正在尝试将产品对象 (:userid) 设置为用户对象 ID (user.id)。到目前为止我已经得到了这个
class Product < ActiveRecord::Base
before_create :set_userid
def set_userid
self.userid = User.new(params[:id])
end
end
在创建产品对象之前是否有其他方法设置值?
Consider using associations 使用像
这样的助手轻松定义模型之间的关系Product
belongs_to :user
User
has_many :products
您的代码将无法运行,因为模型无法访问 params
。因此,您应该在控制器的操作中分配用户实例:
def your_action
...
product = ...
product.user = User.new(params[:id])