I have a user and guideline model.
I would like a user to be able to mark a guideline as their favourite and then view a list of all their favourite guidelines.
It's not quite right. I'm not sure if the 'favourite' action is adding a favourite correctly; or if it is adding correctly it's not displaying correctly in the favourites view (so 'show' action may not be 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, nothing 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"
get "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 do |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 your comment following 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]
is nil
. Post your params from log file.
Or try this:
Change your link to like 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 your earlier case:
@guideline= Guideline.find_all_by_id(params[:guideline_id]) #=> []
current_user.favourite_guidelines << [] #=> Valid and inserting nothing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.