Thursday, 15 April 2010

Favorites model for my rails app -



Favorites model for my rails app -

i have user , guideline model.

i user able mark guideline favourite , view list of favourite guidelines.

it's not quite right. i'm not sure if 'favourite' action adding favourite correctly; or if adding correctly it's not displaying correctly in favourites view (so 'show' action may not right)...

*controller*guidelines_controller.rb

def favourite type = params[:type] if type == "favourite" @guideline= guideline.find_all_by_id(params[:guideline_id]) current_user.favourite_guidelines << @guideline redirect_to :back, notice: 'you favourited #{@guideline.name}' elsif type == "unfavourite" current_user.favourite_guidelines.delete(@guideline) redirect_to :back, notice: 'unfavourited #{@guideline.name}' else # type missing, nil happens redirect_to :back, notice: 'nothing happened.' end end

*controller*favourites_controller.rb

def show @user = user.find_by_profile_name(params[:id]) if @user @guidelines = @user.favourite_guidelines.all render action: :show else render file: 'public/404', status: 404, formats: [:html] end end end

*routes*routes.rb

get "guidelines/favourite" "favourites/show"

*model*user.rb

has_many :guidelines has_many :favourite_guidelines

*model*favourite_guidelines.rb

attr_accessible :guideline_id, :user_id belongs_to :user

*views*guidelines/index.html.erb

<% if current_user %> <%= link_to "favourite", guidelines_favourite_path(guideline, type: "favourite"), method: "get" %> <%= link_to "unfavourite", guidelines_favourite_path(guideline, type: "unfavourite"), method: "get" %>

*views*favourites/show.html.erb

<% if @guidelines %> <% @guidelines.each |guideline| %> <div class="well"> <%= link_to guideline.title, guideline %> <br /> <%= guideline.content %> <br /> added <%= time_ago_in_words(guideline.created_at) %> ago </div> <% end %> <% end %>

as per comment next returns nil:

@guideline= guideline.find_by_id(params[:guideline_id]) #=> nil current_user.favourite_guidelines << nil #gives association mismatch error

i think params[:guideline_id] nil. post params log file.

or seek this:

change link this:

<%= link_to "favourite", guidelines_favourite_path(guideline_id: guideline.id, type: "favourite"), method: "get" %> <%= link_to "unfavourite", guidelines_favourite_path(guideline_id: guideline.id, type: "unfavourite"), method: "get" %>

in before case:

@guideline= guideline.find_all_by_id(params[:guideline_id]) #=> [] current_user.favourite_guidelines << [] #=> valid , inserting nil

ruby-on-rails ruby-on-rails-3

No comments:

Post a Comment