2016-03-21 13 views
1

Bir kullanıcı ve bir proje arasında bir 'aşağıdaki' ilişkiyi kurmak için bir Projeler ve İlişkiler modelim var. İlişki modelinde enum'u kullanarak 'İlişki' için üç rol belirledim ... bunlar yönetici, ortak çalışan ve ziyaretçi. Bununla birlikte, kullanıcı ve proje arasındaki ilişkinin nasıl kurulduğuna bağlı olarak varsayılan rolü belirlemem gerekir. Aşağıdaki basit senaryolar ihtiyaç vardır:Proje oluşturmaya dayalı olarak Enum'u kullanarak Varsayılan Rolü Ayarlama

(a) bir projeyi yaratan bir kullanıcı otomatik olarak projeye takip ediyor ... İlişki rol projesinin oluşturulduktan sonra 'Yönetici' olarak ayarlanması gerekir

(b) sitenin ziyaretçilerinin sadece proje profil sayfasına gider, onlar tıklayabilirsiniz bir aşağıdaki ilişki kurmak için düğmeye 'izleyin' ... Ancak bu 'ziyaretçinin'

İlişki Modeli İlişki rol belirlesin:

class Relationship < ActiveRecord::Base 
    belongs_to :follower, class_name: "User" 
    belongs_to :followed, class_name: "Project" 
    validates :follower_id, presence: true 
    validates :followed_id, presence: true 

    enum role: [:admin, :collaborator, :visitor] 
    after_initialize :set_default_role, :if => :new_record? 

    def set_default_role 
    self.role ||= :admin 
    end 
end 

Re lationships Denetleyici:

class RelationshipsController < ApplicationController 
    before_filter :authenticate_user! 

    def create 
    @project = Project.find(params[:relationship][:followed_id]) 
    current_user.follow!(@project) 
    # relationship.visitor! View railsapps documentation for devise pundit#roles 
    redirect_to @project 
    end 

    def destroy 
    @project = Project.find(params[:id]).followed 
    current_user.unfollow!(@project) 
    redirect_to @project 
    end 

    private 

    def relationship_params 
    params.require(:relationship).permit(:followed_id, :follower_id) 
    end 

Projeler Kontrolörü

class ProjectsController < ApplicationController 
    before_filter :authenticate_user!, only: [:create, :new, :edit, :update, :delete, :followers] 

def create 
    @project = current_user.own_projects.build(project_params) 
    if @project.save 
     if params[:project][:projectimage].present? 
     render :crop 
     else 
     flash[:success] = "You've successfully created a project..." 
     redirect_to @project 
     end 
    else 
     render 'new' 
    end 
    end 

    def update 
    @project = Project.find(params[:id]) 
    if @project.update_attributes(project_params) 
     if params[:project][:projectimage].present? 
     render :crop 
     else 
     flash[:success] = "Project Created" 
     redirect_to @project 
     @project.followers << current_user #this establishes the following relationship as soon as a new project is created between user/project 
     end 
    else 
     render 'edit' 
    end 
    end 

end 

Kullanıcı Modeli:

class User < ActiveRecord::Base 
    has_many :own_projects, :class_name=>'Project' 

    has_many :projects 
    has_many :relationships, foreign_key: "follower_id", dependent: :destroy 

    has_many :followed_projects, through: :relationships, source: :followed 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    def following?(some_project) 
    relationships.find_by_followed_id(some_project.id) 
    end 

    def follow!(some_project) 
    self.relationships.create!(followed_id: some_project.id) 
    relationship.visitor! 
    end 

end 

Ne Ya 'yönetici' olarak varsayılan rolü ayarlamak için benim kodda değiştirmeniz gerekir veya yukarıda belirtilen iki senaryodan yola çıkarak 'ziyaretçi'? Yukarıdaki açıklamalarda anlatıldığı gibi

+1

Neden her zaman yeni bir 'İlişki' oluştururken 'rolünü' belirtmiyorsunuz? Farklı koşullar altında (ilişkinin dışında) farklıysa neden varsayılan değerle uğraşmak zorundasınız? – BoraMa

+0

Eğer after_initialize ve set_default_role sözünü belirtildiği gibi kaldırmış olsaydım (ve sadece --onum rolü: [: admin,: collaborator,: visitor]) ... yeni bir proje için bu ilişkiyi 'admin' rolünü nasıl kurabilirim? yaratıldı?Proje denetleyicisinin veya ilişki denetleyicisinin oluşturma eyleminde? thx – BB500

+1

Evet, demek istediğim buydu. İlgili 'rolü' temelde ilişkinin oluşturulduğu her yerde, ör. 'User' içinde' follow! 'yönteminde: self.relationships.create! (followed_id: some_project.id, role:: visitor) 'veya kontrolörlerde. – BoraMa

cevap

1

, ben rolleri Relationship sınıfa doğasında olmayan koşullara farklı çünkü açıkça role sizin Relationship s oluşturarak belirtmeleri gerekmektedir düşünüyorum. Relationship aracı sizin User ve Project modelleri arasında has many :through birlikte olduğu gibi

Şimdi, sadece aramaları özel dahil aracıyı Relationship açıkça inşa için << kullanarak ancak olmayan projelere kullanıcıları bağlayan standart bir yol kullanamazsınız params (rol gibi).

Sevgiler çözümü birine posted here için analojik olmalıdır:

class Project < ActiveRecord::Base 
    has_many :relationships, foreign_key: :followed_id, dependent: :destroy 
    has_many :users, through: :relationships 
end 

class User < ActiveRecord::Base 
    has_many :relationships, foreign_key: :follower_id, dependent: :destroy 
    has_many :projects, through: :relationships 

    # this will create the relationship association with the 'visitor' role 
    def follow_project!(some_project) 
    self.relationships.create!(followed_id: some_project.id, role: :visitor) 
    # I think you can even omit the ids here and work with objects: 
    # self.relationships.create!(followed: some_project, role: :visitor) 
    end 

    # this will create the relationship association with the 'admin' role 
    def administrate_project!(some_project) 
    self.relationships.create!(followed: some_project, role: :admin) 
    end 

    # this will create the relationship association with the 'collaborator' role 
    def collaborate_on_project!(some_project) 
    self.relationships.create!(followed: some_project, role: :collaborator) 
    end 
end 

class Relationship < ActiveRecord::Base 
    belongs_to :follower, class_name: "User" 
    belongs_to :followed, class_name: "Project" 

    enum role: [:admin, :collaborator, :visitor] 
end 

follow_, administrate_ ve collaborate_on_project! yöntemleri aynı şekilde çalışır ancak ilişkide her setleri farklı rolü. Sonra, sadece bir proje oluştururken örnek 'yönetici' ilişki ayarlamak için, kumandadan uygun olanı arayabilirsiniz:

class ProjectsController < ApplicationController 

    def create   
    # ideally you should wrap multiple separate saves in a transaction so that 
    # either they all succeed or all fail 
    Project.transaction do 
     # this creates a barebone project, without any association 
     @project = Project.create!(project_params) 
     # this associates the project to the current user with admin role 
     current_user.administrate_project!(@project) 
     # ...     
    end 
    end 

end 

ayrıca rails guides mutlaka okuyun lütfen: dikkatle dernekler aracılığıyla.

+0

Yardımlarınız için teşekkürler Bora. – BB500

İlgili konular