읽어 주셔서 감사합니다!내 앱에서 사용자 역할을 구현하는 편리한 방법
나는 현재 내가 구현해야무엇 I "사용자 A와 위치에서 역할을"다음 기능을 시나리오에 의해
을 구현하기 위해 나의 새로운 응용 프로그램에 노력하고 최선의 방법을 찾고 있어요
수행 완료 :
시나리오 : 사용자가 프로필에 새 위치를 추가하면 요청 된 필드 중 하나가 "역할"입니다. 그것은 "게스트", "매니저"또는 "판매자"일 수 있습니다. 모델 측면에서 그의 목표를 달성하는 가장 좋은 방법은 무엇입니까?
def create
@location = Location.new(location_params)
@location.profiles << current_user.profile
#set user role
current_user.profile.profile_location_throughs.where(location_id: location.id).set_role(params[:location][:role])
respond_to do |format|
if @location.save
....
end
end
end
모델 : :
나는 has_many_through의 assosiation와CONTROLLER이 달성 당신이 더 아름 다운 방법을 제안 할 수 :
class Profile < ActiveRecord::Base do
has_many :profile_location_throughs
has_many :locations, through: :profile_location_throughs
end
class Location < ActiveRecord::Base do
has_many :profile_location_throughs
has_many :locations, through: :profile_location_throughs
end
class ProfileLocationThrough < ActiveRecord::Base
# with boolean fields: manager, seller, guest
belongs_to :location
belongs_to :profile
def set_role(role)
case role
when "guest"
self.guest = true
when "seller"
self.seller = true
when "manager"
self.manager = true
end
end
end
=====을 질문
그의 기능을 구현하려면?
캔 사용자는 서로 다른 위치에서 다른 역할을 가지고? 그렇다면 연관을 통해 관리하는 것이 옳습니다. 하지만, 대신 테이블을 통해 각 레코드의 역할 이름을 유지. 'roles' 테이블과 각각의'Role' 모델을 만들고이를 통해 테이블에 연관을 추가하십시오. –
각 역할마다 하나씩 3 개의 다른 필드가 있음을 확인했습니다. 새 역할이 정의 될 때마다 모델에 새 필드를 추가해야하기 때문에 상황이 좋지 않을 수 있습니다. 대신에 싱글 필드'role'을 유지하고 그 안에 "guest", "manager"또는 "seller"를 저장해야합니다. –
예. 한 위치에서 "판매자", 다른 "게스트"등등이 될 수 있습니다. – Art