【问题标题】:How to solve undefined local variable or method error如何解决未定义的局部变量或方法错误
【发布时间】:2016-02-22 07:23:55
【问题描述】:

我有三个表:RMGenericUserProperties

RM 字段:idname

GenericUser 字段:idmobilerm_idname

Properties 字段idimagerm_idgeneric_user_idproperty_name

RM 正在创建GenericUser,因此rm_id 会自动输入到GenericUser 表中。

在通用用户登录并创建属性后,因此当通用用户创建属性时,rm_id 应该从通用用户表中获取,并应输入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_users propertiescontroller:

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(ie; rm_id :4) 保存到属性表字段 rm_id?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activerecord


    【解决方案1】:

    您的错误在于以下几行:

    @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

    【讨论】:

      【解决方案2】:

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

      改变这个,

      @property.rm_id=@gu.rm_id
      

      对此,

       @property.rm_id = @gu
      

      【讨论】:

      • 它作为空插入
      猜你喜欢
      • 2012-06-11
      • 2012-10-14
      • 1970-01-01
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多