【问题标题】:How to display associations from rails console如何从 Rails 控制台显示关联
【发布时间】:2016-07-03 02:17:22
【问题描述】:

联想是我的致命弱点。

我有 3 个模型和控制器:UserListItem

用户可以创建usernamepassword。 List可以创建listname,Item可以创建item_name

理想情况下,列表属于用户。一个项目属于一个列表。列表有很多项目。用户有很多列表。所以我想出了:

class Item < ActiveRecord::Base
  belongs_to :list
  delegate :user, to: :list
end

class List < ActiveRecord::Base
  belongs_to :user
  has_many :items
end

class User < ActiveRecord::Base
  has_many :lists
  has_many :items, through: :lists
end

在 Rails 控制台上,为了确保,我检查了列:

2.2.1 :005 > List.column_names
 => ["id", "name", "user_id", "created_at", "updated_at"] 
2.2.1 :006 > Item.column_names
 => ["id", "item_name", "list_id", "created_at", "updated_at"]     
2.2.1 :007 > User.column_names
 => ["id", "username", "password", "created_at", "updated_at"] 

所以我去创建新的用户、项目和列表:

User.create(username: "iggy2", password: "helloworld") 
#let's say iggy2 has user_id 2.

我想让 iggy2 有一个名为“重要的东西”的列表,其中包含项目“洗碗”。

List.create(name: "Important", user_id: 2 ) #let's say this has id of 1

Item.create(item_name: "Wash dishes", list_id: 1)

我假设 Item 连接到 List 并且 List 连接到 User。但是当我输入 User.last.name 时,我没有看到“重要”,而是得到了 NoMethodError: undefined method 'name'。我在 List.last.item_name 上也遇到了类似的错误

这就是我的架构的样子

create_table "items", force: :cascade do |t|
    t.text     "item_name"
    t.integer  "list_id"
    t.datetime "created_at",                 null: false
    t.datetime "updated_at",                 null: false
  end

  create_table "lists", force: :cascade do |t|
    t.string   "name"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "username"
    t.string   "password"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

我的代码缺少什么?我的假设错了吗?如何让User.last.name 甚至User.last.item_name 显示最后一个用户的项目名称或列表名称?

【问题讨论】:

    标签: ruby-on-rails associations polymorphic-associations


    【解决方案1】:

    您的代码是正确的,但您的假设是错误的。 User.last 返回一条用户记录,因此您在访问关联记录中的方法时将得到NoMethodError

    我想你想要的如下:

    List.where(user_id: User.last.id).pluck(:name) # Return all list names belong to last user
    
    id = List.find_by(user_id: User.last)
    Item.where(list_id: id).pluck(:item_name) # Return all item names belong to last user
    

    【讨论】:

    • 成功了。谢谢!我只是想到了一个后续问题。由于我仍在学习多态性,我不确定是否可能,但是是否可以使用命令 User.last.item_name 或 User.last.name (name = list name) 并返回一个值? (意思是,是否有可能直接从用户转到另一个关联项目的属性?),还是必须通过您上面的答案提到的过程?非常感谢!
    • 当然你可以在这里应用多态关联,即Item可以同时属于UserListguides.rubyonrails.org/…应该举个例子
    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2015-11-07
    相关资源
    最近更新 更多