【问题标题】:Rails ActiveRecord - Users behave as Team after migrationsRails ActiveRecord - 迁移后用户表现得像团队一样
【发布时间】:2018-12-19 18:26:34
【问题描述】:

我有一个用户表和一个团队表。 users 表有一个名为 team_id 的列。但现在的目标是让用户拥有多个团队。

所以我使用迁移创建了 user_teams 表,如下所示:

class CreateUserteams < ActiveRecord::Migration[5.0]
  def change
    create_table :user_teams do |t|
      t.integer :user_id
      t.integer :team_id

      t.timestamps
    end
  end
end

而我的代码如下:

models/user.rb

class User < ApplicationRecord

#belongs_to :team

# should now have multiple teams
has_many :user_teams
has_many :teams, through: :user_teams

models/team.rb

class Team < ApplicationRecord

has_many :members, foreign_key: "team_id", class_name: "User"

has_many :user_teams
has_many :users, through: :user_teams

models/user_teams.rb(新文件)

class UserTeam < ApplicationRecord
  belongs_to :user
  belongs_to :team
end

(这很好)要邀请用户加入团队,我向他发送邀请,如果他接受,我将他添加到新的 users_team 表中:

controllers/team_invites_controller.br

    def accept
    user = @team_invite.user
    @team_invite.update(status: TeamInvite.statuses[:accepted])
    user.team_id = @team_invite.team_id
    user.company_id = @team_invite.team.company_id
    user.teams << Team.find(user.team_id)
    user.save(:validate => false)


    respond_to do |format|
      if user.shadow?
        format.html {
          redirect_to new_user_registration_path({
            :email => user.email,
            :role => user.main_role,
          })
        }
      else
        format.html { redirect_to dashboard_root_path, notice: 'Invite accepted' }
      end
      format.json { head :no_content }
    end
  end

问题是,现在“用户”不知何故变成了团队而不是用户,并且使用“user.something”破坏了所有代码。也正因为如此,我无法访问用户方法,因为“用户”不再是用户而是团队。

例如,现在:

<% if user.photo.exists? %>

给予:

Team:0x00007f381dea4708 的未定义方法 `photo'

或者:

<% if current_user.teams.members.count > 1 %>

给予:

未定义的方法“成员” Team::ActiveRecord_Associations_CollectionProxy:0x00007f3845954eb0 你的意思是?会员?

为什么 users.something 现在表现为一个团队?我已经重新进行了迁移并得到了同样的错误。知道这是怎么发生的以及如何解决吗?如何正确访问用户属性和方法? 谢谢

编辑 开

<% if user.photo.exists? %>

它的目的是显示另一个用户的图像,它给出了未定义的方法“照片”错误。但是如果我使用(虽然我不想)

<% if current_user.photo.exists? %>

它有效。怎么会?

【问题讨论】:

  • 如果您在user.teams &lt;&lt; Team.find(user.team_id) 周围显示代码(通过使用标签正下方的edit 链接编辑您的问题),它可能会有所帮助。
  • @jvillian 我已经编辑了代码。虽然我认为这不是问题,因为我可以邀请人加入。问题是用户和团队之间的关联。
  • 为什么还要在 users 表中保存 team_id 列? user.team_id = @team_invite.team_id
  • @ShiraElitzur 稍后我会将其重命名为 favorite_team_id。
  • 你能提供更多关于user.photo.exists?的上下文吗?

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


【解决方案1】:

您的用户有多个teams,因此current_user.teams 不再是Team,它是一个集合代理,可以从那里访问各个团队,具体取决于您可以使用的逻辑:

<% if current_user.teams.any?{|team| team.members.count > 1 } %>

(请注意,如果有很多团队,此代码可能效率低下)

【讨论】:

    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多