我有一个用户和指南模型。
我希望用户能够将指南标记为他们的最爱,然后查看他们最喜欢的所有指南的列表。
这不太对。我不确定“收藏夹”操作是否正确添加了收藏夹;或者,如果添加正确,则无法在收藏夹视图中正确显示(因此“显示”操作可能不正确)...
*控制器*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
*控制器*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.rb
get "guidelines/favourite"
get "favourites/show"
*型号*user.rb
has_many :guidelines
has_many :favourite_guidelines
*模型*favourite_guidelines.rb
attr_accessible :guideline_id, :user_id
belongs_to :user
*观点*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" %>
*意见 *收藏夹/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 %>