我正在尝试以用户和团队为例,在Rails中建立一对多关系。
在我的示例中,用户只能有一个团队,而团队可以有多个用户。用户包含team_id字段
模式:
create_table "teams", force: :cascade do |t|
t.string "slack_team_id"
t.string "name"
t.boolean "active", default: true
t.string "domain"
t.string "token"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "bot_user_id"
t.string "activated_user_id"
t.string "activated_user_access_token"
t.string "question_time", default: "10:00", null: false
end
create_table "users", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "user_name"
t.string "nickname"
t.string "slack_user_id"
t.bigint "team_id"
t.index ["team_id"], name: "index_users_on_team_id"
end
add_foreign_key "users", "teams"
团队模型:
class Team < ApplicationRecord
has_many :users
end
用户模型:
class User < ApplicationRecord
belongs_to :team
end
编辑:
什么不起作用?
=>当我尝试执行team.users
时,它提示用户功能为NoMethodError。
我相信这是因为我正在使用Slack Ruby bot gem(https://github.com/slack-ruby/slack-ruby-bot-server)
我感觉它正在使用此团队模型,而不是我创建的团队模型。 关于如何说应该使用自己的团队模型的任何指示。
编辑2 =>
我如何访问team.users? slack-ruby-bot gem提供了扩展slack命令的功能,当用户键入该命令时,它将提供回调。
我在这里将其用作:
class Give < SlackRubyBot::Commands::Base
def self.call(client, data, match)
team = client.owner
puts team.users
end
end
如您所见,slack-ruby-bot的内部实现返回了团队。
请帮助我了解为什么这不起作用
答案 0 :(得分:0)
希望对您有帮助。
相对而言,我们可以访问以下数据
Team.all[0].users
Team.first.users
User.first.team
Team.all.map{|t| t.users}