我有一个用户和指南模型。
我希望用户能够将指南标记为他们的最爱,然后查看所有他们喜爱的指南列表。
这不太对劲。我不确定'最喜欢'的动作是否正确添加了一个喜欢的;或者如果添加正确,它在收藏夹视图中无法正确显示(因此'show'操作可能不正确)...
* 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.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
* 视图 *准则/ 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 %>
答案 0 :(得分:1)
根据您的评论,返回nil
:
@guideline= Guideline.find_by_id(params[:guideline_id]) #=> nil
current_user.favourite_guidelines << nil #Gives association mismatch error
我认为params[:guideline_id]
是nil
。从日志文件中发布你的参数。
或试试这个:
将您的链接更改为:
<%= 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" %>
在您之前的案例中:
@guideline= Guideline.find_all_by_id(params[:guideline_id]) #=> []
current_user.favourite_guidelines << [] #=> Valid and inserting nothing