我按照托马斯here
发布的第一个答案中的步骤进行操作我可以进入Heroku控制台并手动用户喜欢的phootos,这样模型设置正确且有效但我最喜欢/不喜欢的链接不起作用。
<p><strong>Picture:</strong></p>
<%= image_tag(@phooto.picture) %>
<%= link_to("< Previous", @phooto.previous) if @phooto.previous %>
<%= link_to("Next >", @phooto.next) if @phooto.next %>
<% if current_user %>
<%= link_to "favorite", favorite_phooto_path(@phooto, type: "favorite"), method: :put %>
<%= link_to "unfavorite", favorite_phooto_path(@phooto, type: "unfavorite"), method: :put %>
<% end %>
Heroku Log
Started PUT "/phootos/24/favorite?type=favorite"
Completed 500 Internal Server Error in 2ms (ActiveRecord: 0.6ms)
ActiveRecord::AssociationTypeMismatch (Phooto(#70057240967940) expected, got NilClass(#70057199933300)):
app/controllers/phootos_controller.rb:29:in `favorite
PhootosController
def show
@phooto = Phooto.find(params[:id])
end
def favorite
type = params[:type]
if type == "favorite"
**rb.29** current_user.favorites << @phooto
redirect_to :back, notice: 'You successfully favorited #{@phooto.name}'
elsif type == "unfavorite"
current_user.favorites.delete(@phooto)
redirect_to :back, notice: 'You successfully unfavorited #{@phooto.name}'
else
redirect_to :back, notice: 'Nothing happened.'
end
end
Phootos / show.html.erb
<p><strong>Picture:</strong></p>
<%= image_tag(@phooto.picture) %>
<%= link_to("< Previous", @phooto.previous) if @phooto.previous %>
<%= link_to("Next >", @phooto.next) if @phooto.next %>
<% if current_user %>
<%= link_to "favorite", favorite_phooto_path(@phooto, type: "favorite"), method: :put %>
<%= link_to "unfavorite", favorite_phooto_path(@phooto, type: "unfavorite"), method: :put %>
<% end %>
的routes.rb
resources :users
resources :phootos
resources :phootos do
put :favorite, on: :member
end
答案 0 :(得分:1)
老实说,更好的模式是根据HTTP verb匹配favorite
路由:
#config/routes.rb
resources :users
resources :phootos do
match :favorite, on: :member, via: [:put, :delete]
end
这将取消路径中的type
参数(导致问题):
<% if current_user %>
<%= link_to "favorite", favorite_phooto_path(@phooto), method: :put %>
<%= link_to "unfavorite", favorite_phooto_path(@phooto), method: :delete %>
<% end %>
您必须更改控制器才能处理请求和变量:
def favorite
@phooto = Phooto.find params[:id]
if request.put?
current_user.favorites << @phooto
redirect_to :back, notice: 'You successfully favorited #{@phooto.name}'
elsif request.delete?
current_user.favorites.delete(@phooto)
redirect_to :back, notice: 'You successfully unfavorited #{@phooto.name}'
else
redirect_to :back, notice: 'Nothing happened.'
end
end
答案 1 :(得分:0)
只需将此行添加为Public Class y
Public Class x //class inside of class
End Class
End Class
Public Class Form1
Public Sub Form1_Load(<params>) Handles Me.Load
Dim yinst As y = New y()
Dim xinst As x = New y.x()
MsgBox(yinst.xinst) //instance inside of instance
End Sub
End Class
favorite
方法的第一行
PhootosController