In Rails, an image link can be created that will allow users to update an attribute. In the following code, users can click on an image to mark a particular screencast as watched. When the screencast is marked as watched, a different icon is shown that can be used to mark the screencast as not watched:

view

- if cast.watched?
  = link_to image_tag('watched.png'), cast_path(cast, cast: {watched: false}), method: :put
- else
  = link_to image_tag('unwatch.png'), cast_path(cast, cast: {watched: true}), method: :put

controller

class CastsController < ApplicationController
  
  def update
  @cast = Cast.find(params[:id])

    if @cast.update(params.require(:cast).permit(:title, :episode, :watched, :favorite))
      flash[:success] = "Status changed"
      redirect_to root_path
    else
      flash[:danger] = "There was a problem changing the status"
    end
  end

end

Test

require 'spec_helper'

describe CastsController do
  describe 'PUT update' do
    it 'updates the post' do
      cast = Fabricate(:cast, watched: false)
      put :update, id: cast.id, cast: {watched: true}
      expect(cast.reload.watched).to eq(true)
    end
  end
  
end

This test uses the RSpec framework (rspec-rails gem) and the fabrication gem to generate fixtures.

Tags: , , ,

In categories: Rails, web development

COMMENTS

LEAVE A REPLY

Only the name field is required. Your email will not be published.