RoR Create and Update

0

I am developing a system in ROR and I have a news table in the bank, being that there is a highlight column and every time the admin registers another notice as highlight even if there is already one in the bank, the controller has to remove the one that was already featured and put this new. NOTE: The highlighted field is Boolean so it will only change from "true" to "false".

Controller

def create
    # @notice = Notice.new(notice_params)
    featured = params[:notice][:featured]
    category = params[:notice][:category_id]
    user = current_user.secretary.prefecture.county_id
      if featured = 1
        @notice = Notice.where(county_id: user, category_id: category,  featured: true)
        if @notice.present?
          @notice = Notice.find(@notice.id).update(featured: false) rescue nil
        end
      end
 end
    
asked by anonymous 10.05.2018 / 15:30

1 answer

0

After a lot of trying I was able to execute. Thanks!

  def create
  featured = params[:notice][:featured]
  puts featured
  category = params[:notice][:category_id]
  user = current_user.secretary.prefecture.county_id

    if featured.to_s == "1"
      puts "destaque selecionado, buscando destaque ativo"
      @n = Notice.where(county_id: user, category_id: category,  featured: true)
      # b = @n
      puts "Registo encontrado ", @n.ids
      if [email protected]?
        puts "A busca n foi vazia"
        a = @n.where(id: @n.ids).update(featured: false)
        puts "O registo ", @n.ids, " foi alterado"
      end
    end
    @notice = Notice.new(notice_params)
    @notice.county_id = user
      respond_to do |format|
      if @notice.save
          format.html { redirect_to action: :index}
          format.json { render :show, status: :created, location: @notice }
        # format.html { redirect_to @notice, notice: 'Notice was successfully created.' }
        # format.json { render :show, status: :created, location: @notice }
        else
          format.html { redirect_to action: :index}
          format.json { render :show, status: :created, location: @notice }
        # format.html { render :new }
        # format.json { render json: @notice.errors, status: :unprocessable_entity }
        end
      end
  end
    
11.05.2018 / 18:09