关于前面的一个问题:子用户和设计,OP询问如何让子用户参与设计。给出的答案是在用户模型中建立一个belongs_to has_many关系,因此:
class User
belongs_to :parent, :class_name => 'User'
has_many :children, :class_name => 'User'
...
end并据此修改控制器:
class UsersController < ApplicationController
def new
@user = User.new
@user.parent_id = params[:parent_id]
respond_to do |format|
end
end这似乎是我想要做的事情的完美解决方案,但我很难思考如何进行迁移才能完成这项工作。我使用的是Devise,我的模型和users表已经存在,所以我需要实际生成一个迁移。它会像向parent_id表中添加一个users列一样简单吗?使用add_reference迁移不是更好吗?
我试过这个:
class AddUsersToUser < ActiveRecord::Migration[6.0]
def change
add_reference :users, :user, foreign_key: true
end
end但是我得到的是user_id字段,而不是parent_id字段,因此引用parent_id的任何代码(如视图或助手)都会出现错误。
未定义的方法‘`parent_id’。
有人能帮助我理解什么迁移是必要的,使这一工作吗?
还是有更好的方式来设置子用户的设计?
如果您需要它,下面是我的应用程序中的相关文件:
路线:
Rails.application.routes.draw do
devise_for :users, controllers: {
:registrations => "users/registrations"
}
...
end主计长:
class Users::RegistrationsController < Devise::RegistrationsController
# before_action :configure_sign_up_params, only: [:create]
# before_action :configure_account_update_params, only: [:update]
# GET /resource/sign_up
def new
build_resource
resource.parent_id = params[:parent_id]
yield resource if block_given?
respond_with resource
end
end模型:
class User < ApplicationRecord
belongs_to :parent, :class_name => 'User'
has_many :children, :class_name => 'User', dependent: :destroy
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
:lockable, :timeoutable, :trackable
end生成错误的助手:
module UsersHelper
# Returns the Gravatar for the given user.
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=40&d=blank"
image_tag(gravatar_url, class: "gravatar")
end
def current_user_is_head_of_household
current_user.parent_id.nil?
end
def current_user_is_member_of_household
!current_user.parent_id.nil?
end
end调用current_user_is_head_of_household的视图
<h1>Lobby</h1>
<p>This is slated to be the jumping off point (home) where members can access the blog, training, personal information tracker and the various calculators.</p>
<% if current_user_is_head_of_household %>
<%= link_to "Add user to your household", new_user_registration_path %>
<% end %>最后抛出的错误:
未定义的方法`parent_id‘for #您的意思是?亲本parent= 提取源(第11行):9 10 def current_user_is_head_of_household 11 current_user.parent_id.nil? 12 end 13 14 def current_user_is_member_of_household
发布于 2019-12-12 11:22:46
迁移到添加父引用&外键
class AddParentToUser < ActiveRecord::Migration[6.0]
def change
add_reference :users, :parent, index: true
add_foreign_Key :users, :users, column: :parent_id
end
end用户模型关联
belongs_to :parent, :class_name => 'User', optional: true
has_many :children, :class_name => 'User', foreign_key: :parent_idhttps://stackoverflow.com/questions/59298713
复制相似问题