如何解决未定义的局部变量或方法错误

How to solve undefined local variable or method error

我有三个 table:RMGenericUserProperties

RM 字段:idname

GenericUser 字段:idmobilerm_idname.

Properties 字段 idimagerm_idgeneric_user_idproperty_name.

RM 正在创建 GenericUser,因此 rm_id 会自动输入 GenericUser table.

通用用户登录并创建 属性 后,因此当通用用户创建 属性 时,rm_id 应从通用用户 table 获取并应输入 属性 table 字段,其中 rm_id 是。

我有这样的模型关系

class Rm < ActiveRecord::Base
    acts_as :user
    has_many :generic_users
end

class Property < ActiveRecord::Base
    belongs_to :generic_user
end

class GenericUser < ActiveRecord::Base
    belongs_to :rm
    has_many :properties
end

我的generic_userspropertiescontroller:

def create
    @property = Property.new(property_params)
    @gu=GenericUser.select(:rm_id).where(:id=>current_user.specific.id)
    @property.rm_id=@gu.rm_id
   logger.info @gu.inspect
    logger.info @property.rm_id.inspect
    if @property.save
        redirect_to  :back, notice: 'Property was successfully created.' 
    else
        render :new
    end
end

我收到这个错误:

当我检查@gu 我得到这个

#<ActiveRecord::Relation [#<GenericUser id: 1, mobile: "8776766777", address: "reewtrwt", created_at: "2016-02-18 07:41:06", updated_at: "2016-02-19 08:59:13", dob: "", rm_id: "4", category_id: "1",>]> Completed 500 Internal Server Error in 73ms (ActiveRecord: 1.9ms)

我如何将此 GenericUser rm_id(即;rm_id :4)保存到属性 table 字段 rm_id?

您已经在@gu 中选择了rm_id。您无需再次调用它。

改变这个,

@property.rm_id=@gu.rm_id

为此,

 @property.rm_id = @gu

你的错误在这些行中:

@gu = GenericUser.select(:rm_id).where(:id=>current_user.specific.id)
@property.rm_id = @gu.rm_id

解释:

@gu 返回为 Active Record Relations,因此您无法调用 @gu.rm_id

解决方案 - 试试这样:

@gu = GenericUser.find(current_user.specific.id)
@property.rm_id = @gu.rm_id

@gu 现在是 GenericUser,因此您可以在其上调用 rm_id