我是ROR的新手,我正在努力通过遍历所有的stackoverflow和github页面来解决这个问题,我保证我已经完成了所有这些但是仍然无法找到我的问题的解决方案。我希望你们能帮助我。
问题是,在我实现了thumbs_up gem后,我按照Brady的说明进行了操作: Clarification on how to use "thumbs_up" voting gem with Rails 3
但我的视图页面会显示错误消息:
No route matches {:action=>"vote_up", :controller=>"posts", :id=>nil}
我检查了rake路线,并且那里有vote_up_post路径,所以我试着去
http://0.0.0.0:3000/posts/vote_up and this shows up:
ActiveRecord::RecordNotFound in PostsController#show
Couldn't find Post with id=vote_up
以下是我的观点 - index.html.erb
<%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %>
posts_controller.rb
def vote_up
begin
current_user.vote_for(@post = Post.find(params[:id]))
render :nothing => true, :status => 200
rescue ActiveRecord::RecordInvalid
render :nothing => true, :status => 404
end
end
model - user.rb
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
acts_as_voter
model - post.rb
attr_accessible :title, :source, :description, :imageurl, :link
validates :title, presence: true, uniqueness:true, length: { maximum: 70 }
validates :source, presence: true, length: { maximum: 20 }
validates :description, presence: true, length: { maximum: 240 }
validates :imageurl, presence: true
validates :link, presence: true
default_scope order: 'posts.created_at DESC'
acts_as_voteable
的routes.rb
devise_for :users
resources :posts do
member do
post :vote_up
end
end
devise_scope :user do
get "sign_in", :to => "devise/sessions#new"
get "sign_out", :to => "devise/sessions#destroy"
get "sign_up", :to => "devise/registrations#new"
end
resources :submissions
match '/submit', to: 'submissions#new'
match '/post', to: 'posts#new'
很抱歉问这么愚蠢的问题,真的很感谢你们的帮助。
答案 0 :(得分:0)
你得到的错误
No route matches {:action=>"vote_up", :controller=>"posts", :id=>nil}
来自
行<%= link_to('vote for this post!', vote_up_post_path(@post), :method => :post) %>
路由器尝试查找id为nil的路由,这里你的id是“@post”。首先要做的是搜索@post变量的位置,并检查它不是零。删除link_to并设置一个简单的
<%= @post.inspect %>
只是在您的视图顶部将回答您:如果您的页面显示“nil”,则@post未在您的控制器上初始化:)
答案 1 :(得分:0)
将您的routes.rb
更改为:
resources :posts do
collection do
get :vote_up
end
end
错误Couldn't find Post with id=vote_up
表示vote_up
是您的帖子控制器的成员,而不是。
因此,如果您将操作vote_up
设为集合类型而不是成员,那么一切都会好起来。
现在,如果你点击了网址:
http://0.0.0.0:3000/posts/vote_up
这显示:
vote_up
将不再被视为ID。
ActiveRecord::RecordNotFound
是因为vote_up
被视为您的帖子模型的成员ID。并且在帖子模型中尝试找到vote_up
作为ID会给您记录未找到,因为它永远不会是您的ID。