M
M
Mydrug2019-03-25 21:08:56
Ruby on Rails
Mydrug, 2019-03-25 21:08:56

Disable editing and deleting comments in Rails in Devise access problem?

Such a question, I want to make a ban on editing someone else's comment, but it turns out that I can’t even edit my own or delete it, here is the comment controller code

class CommentsController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show]
  
  def create
  @post=Post.find(params[:post_id])
  @comment = @post.comments.new(comment_params.merge(user_id: current_user.id))
  
  if @comment.save
   redirect_to post_path(@post)
  else
    render :edit
  end
end
  def destroy
  @post = Post.find(params[:post_id])
    @post.comments.find(params[:id]).destroy
  redirect_to post_path(@post)
  end
def update
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])

if (@comment.update(comment_params))
redirect_to post_path(@post)
else
render 'edit'
end
end


  def edit
 @post = Post.find(params[:post_id]) 
  if @post.comments==current_user.id
    @comment = @post.comments.find(params[:id])
    else
        redirect_to @post
     end
  
  end 


  private def comment_params 
   params.require(:comment).permit(:username, :body, :image)	
end
end

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
alfss, 2019-03-26
@alfss

@post.comments==current_user.id - а зачем вы объект со значением сравниваете?

Сергей Еремин, 2016-12-23
@Sergei_Erjemin

Все такие селекты за отдельные периоды собираешь юнионами... Все...

A
AlikDex, 2016-12-23
@AlikDex

группировать по дням, выбирать за последнюю неделю, считать подписчиков
т.е. примерно

SELECT DATE(FROM_UNIXTIME(`created_at`)) AS `dt`, COUNT(`id`) AS `cnt`
FROM `account_analytics`
WHERE `created_at` > UNIX_TIMESTAMP(DATE_SUB(CURRENT_DATE, INTERVAL 6 DAY))
GROUP BY DATE(FROM_UNIXTIME(`created_at`));

Не проверял, не знаю работает или нет, но думаю ход мысли понятен.
Либо может GROUP BY `dt` сработает, чтоб не считать снова.
Для аккаунта тож самое будет, тока с указанием ида аккаунта во WHERE,
И для именно этого случая я бы делал колонку created_at не timestamp, а полноценной datetime и юзал мускульные функции без преобразований. Это проще намного, хоть и немного затранее по памяти.

M
mletov, 2016-12-23
@mletov


Для первой задачи не получается составить запрос((
1. Необходимо получить 7 записей (неделя) из БД, в каждой записи должна быть дата и кол-во подписчиков для всех аккаунтов.
Не совсем понял условие
count - это общее количество подписчиков на этот день (с учетом подписавшихся в предыдущие дни) или количество новых подписчиков, которые подписались в этот день?
Если второе
SELECT DATE(FROM_UNIXTIME(`created_at`)), SUM(count) AS cnt
FROM account_analytics
GROUP BY DATE(FROM_UNIXTIME(`created_at`))
ORDER BY DATE(FROM_UNIXTIME(`created_at`)) DESC
LIMIT 0, 7

Учитываются ли отписавшиеся?
================================================================================
UPDATE 1
SELECT DATE(FROM_UNIXTIME(account_analytics.created_at)) AS dt,
     SUM(account_analytics.count) AS sumAll
FROM account_analytics
INNER JOIN
(
  -- Берем последний обход по каждому аккаунту за каждый день
  SELECT account_id,
       DATE(FROM_UNIXTIME(`created_at`)) AS dt,
       MAX(created_at) AS dtMax
  FROM account_analytics 
  GROUP BY account_id,
       DATE(FROM_UNIXTIME(`created_at`))
) AS t1		 
ON account_analytics.account_id = t1.account_id
AND account_analytics.created_at = t1.dtMax
GROUP BY DATE(FROM_UNIXTIME(account_analytics.created_at))
ORDER BY  DATE(FROM_UNIXTIME(account_analytics.created_at)) DESC
LIMIT 0, 7

A
Angel1, 2016-12-23
@Angel1

Done, the request is not very nice, but it works. Next, I will replace the timestamp with date. The request took 0.0806 seconds.
1. It is necessary to get 7 records (week) from the database, each record must contain the date and number of subscribers for all accounts .

SELECT
        `date`,
        SUM(`count`) AS `count`
FROM (
        SELECT * FROM (
            SELECT
                DATE(FROM_UNIXTIME(`created_at`)) AS `date`, 
                CONCAT(`account_id`, DATE(FROM_UNIXTIME(`created_at`))) AS `a`,
                `count_followers`
            FROM 
                `account_analytics`
            WHERE 
                `created_at` > UNIX_TIMESTAMP(DATE_SUB(CURRENT_DATE, INTERVAL 6 DAY))
            ORDER BY `id` DESC
    	) `t1` GROUP BY `a` 
) `t2` 
GROUP BY `date` DESC

2. It is necessary to get 7 records (week) from the database, each record must contain the date and number of subscribers for a particular account .
SELECT
        `date`,
        SUM(`count`) AS `count`
FROM (
        SELECT * FROM (
            SELECT
                DATE(FROM_UNIXTIME(`created_at`)) AS `date`, 
                CONCAT(`account_id`, DATE(FROM_UNIXTIME(`created_at`))) AS `a`,
                `count_followers`
            FROM 
                `account_analytics`
            WHERE 
                `account_id` = 3 AND `created_at` > UNIX_TIMESTAMP(DATE_SUB(CURRENT_DATE, INTERVAL 6 DAY))
            ORDER BY `id` DESC
    	) `t1` GROUP BY `a` 
) `t2` 
GROUP BY `date` DESC

The algorithm is as follows:
1. All records for 7 days are collected, the column with the date and account id are merged into one line. All records are sorted in descending order
2. Then the rows are grouped by the column in which the date and account id are connected.
3. The result of the two actions above is grouped by date (in descending order)
. Now there is a question about optimization. It turns out that the first query fetches ~8k records, then the second and third fetch leaves only 7 records.
SELECT
    	DATE(FROM_UNIXTIME(`created_at`)) AS `date`, 
    	CONCAT(`account_id`, DATE(FROM_UNIXTIME(`created_at`))) AS `a`,
    	`count_followers`
FROM 
    	`account_analytics`
WHERE 
    	`account_id` = 3 AND `created_at` > UNIX_TIMESTAMP(DATE_SUB(CURRENT_DATE, INTERVAL 6 DAY))
ORDER BY `id` DESC

So I assume that this query cannot be optimized without taking into account the assignment of indexes and changing the type of the created_at field from int to datetime?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question