【问题标题】:Problems after adding has_many: and belongs_to:添加has_many:和belongs_to后的问题:
【发布时间】:2014-03-20 04:12:35
【问题描述】:

我之前创建了以下没有 has_many: 和 belongs_to: 属性的模型。他们之前工作得很好,但在添加 has_many 和 belongs_to 之后就不行了,它不起作用。我有一个联合表,然后试图通过 has_many: 和 belongs_to: 将其与用户关联,如下所示。

这是属于教室的:

belongs_to :user

belongs_to :first
belongs_to :second
belongs_to :third

当我之前通过

创建对象时
attributes = user_params
@user = User.find_by_id(attributes[:user_id].to_i)
attributes = classroom_params
@classroom = @user.classroom.where(:first_id => attributes[:first].to_i,
                                :second_id => attributes[:second].to_i,
                                :third_id => attributes[:third].to_i).first_or_create

这不起作用后,我尝试了以下方法:

@classroom = @user.classrooms.create(:first_id => attributes[:first].to_i,
                                :second_id => attributes[:second].to_i,
                                :third_id => attributes[:third].to_i)

并得到了这个错误,即使它以前工作过:

ActiveRecord::UnknownAttributeError (unknown attribute: first_id):
  app/controllers/api/v1/classroom_controller.rb:30:in `create'

我想让它与 first_or_create 一起使用,但第二种方法是一个不错的起点

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    如果您要对此进行测试,则需要进一步简化:

    @classroom = @user.classrooms.create(first_id: "1",second_id: "2", third_id: "3")
    

    这将显示问题出在您的变量还是您的表格上。您的错误表明您的 Classroom 模型无法识别 first_id 属性。这表明您的classrooms db 中没有first_id

    在您的 rails 控制台中,您应该这样做:

    Classroom.column_names
    #-> outputs column names
    

    如果这返回带有first_id 等的列名,则说明您的关联有问题。但我想你没有设置 first_idsecond_idthird_id

    【讨论】:

    • 所以我肯定有一个 first_id:,我检查了 Classroom.column_names。奇怪的是,在我添加 has_many: 和 belongs_to: 之前,教室还在工作。我将如何解决关联问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多