ruby on rails - Implement "add to favorites" -
i creating app user can favorite room. started has_and_belongs_to_many association. noticed tricky implement remove button drestroy. decided time has_many through association. have users should add rooms favorite or wishlist. unfortunately when click on favorite button getting error:
what missing how can make work?
if need further information let me know. have used direction.
implement "add favorites" in rails 3 & 4
favorite_room.rb
class favoriteroom < applicationrecord belongs_to :room belongs_to :user end
room.rb
belongs_to :user has_many :favorite_rooms has_many :favorited_by, through: :favorite_rooms, source: :user
user.rb
has_many :rooms has_many :favorite_rooms has_many :favorites, through: :favorite_rooms, source: :room
routes.rb
resources :rooms put :favorite, on: :member end
rooms_controller.rb
before_action :set_room, only: [:show, :favorite] ... ... def favorite type = params[:type] if type == "favorite" current_user.favorites << @room redirect_to wishlist_path, notice: 'you favorited #{@room.listing_name}' elsif type == "unfavorite" current_user.favorites.delete(@room) redirect_to wishlist_path, notice: 'unfavorited #{@room.listing_name}' else # type missing, nothing happens redirect_to wishlist_path, notice: 'nothing happened.' end end private def set_room @room = room.find(params[:id]) end
show.html.erb
<% if current_user %> <%= link_to "favorite", favorite_room_path(@room, type: "favorite"), method: :put %> <%= link_to "unfavorite", favorite_room_path(@room, type: "unfavorite"), method: :put %> <% end %>
create_favorite_rooms.rb (migration file)
class createfavoriterooms < activerecord::migration[5.0] def change create_table :favorite_rooms |t| t.integer :room_id t.integer :user_id t.timestamps end end end
Comments
Post a Comment