Rails 5: ассоциация между пользователем и страницами, модератором которых он является - PullRequest
0 голосов
/ 02 июня 2018

В моем приложении rails есть модель User и модель Coin, а моделью Coin являются страницы, которые пользователь может модерировать.Пользователь должен иметь возможность модерировать несколько страниц.

Так что, если есть Coin_A, Coin_B, Coin_C и Coin_D, User1 может модерировать Coin_A, а Coin_D и User2 могут модерировать Coin_B

Я установил ассоциацию has_and_belongs_to_many между двумя моделями.

Теперь я застрял, пытаясь понять, как назначить модератора для страниц.В идеале я хотел бы иметь возможность выбрать из списка монет на странице профиля пользователя, чтобы добавить пользователя в качестве модератора.Является ли has_and_belongs_to_many правильным путем?Как я могу это сделать?

User.rb

class User < ApplicationRecord
  acts_as_votable
  has_many :questions, dependent: :destroy
  has_many :events, dependent: :destroy
  has_many :links, dependent: :destroy
  has_many :posts, dependent: :destroy
  has_and_belongs_to_many :coins
  has_and_belongs_to_many :users

  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable,
     :validatable, authentication_keys: [:login]

  validates :username, presence: :true, uniqueness: { case_sensitive: false }
  validates_format_of :username, with: /^[a-zA-Z0-9_\.]*$/, :multiline => true
  validate :validate_username

  def validate_username
    if User.where(email: username).exists?
      errors.add(:username, :invalid)
    end
  end

  def login=(login)
    @login = login
  end

  def login
    @login || self.username || self.email
  end

  def self.find_for_database_authentication(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    elsif conditions.has_key?(:username) || conditions.has_key?(:email)
      where(conditions.to_h).first
    end
  end

end

Coin.rb

class Coin < ApplicationRecord
  validates :currency_name, presence: true
  has_many :questions, dependent: :destroy
  has_many :events, dependent: :destroy
  has_many :links, dependent: :destroy
  mount_uploader :picture, PictureUploader
  has_and_belongs_to_many :genres
  validate :picture_size

  private
    def picture_size
      if picture.size > 5.megabytes
        errors.add(:picture, "Picture must be smalled than 5MB.")
      end
    end
end

coins_controller.rb

class CoinsController < ApplicationController

  load_and_authorize_resource param_method: :question_params
  before_action :find_coin, only: [:edit, :update, :destroy ]
  before_action :authenticate_user!, except: [:index, :create, :show]

  def index      
    @search = Coin.ransack(params[:q])
    @coins = @search.result(distinct: true)
  end

  def new
    @coin = Coin.new
  end

  def create
    @coin = Coin.new(coin_params)
    if @coin.save
        flash[:success] = "Coin created"
        redirect_to @coin
    else
        render 'new'
    end
  end

  def show
    @coin = Coin.find(params[:id])
  end

  def edit
    authorize! :update, @coin
  end

  def update
    if @coin.update(coin_params)
      redirect_to @coin
    else
      render 'edit'
    end     
  end

  def destroy
    Coin.find(params[:id]).destroy
    redirect_to coins_url
  end

  private

    def coin_params
        params.require(:coin).permit(:currency_name, :currency_abbrev, :working_product, :founder, :mineable, :date_of_ico, :website, :accepted, :picture, :question1, :question2, :question3, :question4, genre_ids:[])
    end

    def find_coin
        @coin = Coin.find(params[:id])
    end
end

1 Ответ

0 голосов
/ 02 июня 2018

Я не уверен, что понимаю ваш вопрос.Какое отношение имеет монета к модератору?Похоже, у монеты есть один модератор.Если это так, то вы можете захотеть

class Coin...
  belongs_to :moderator, class_name: 'User'

class User...
  has_many :moderated_coins, class_name: 'Coin'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...