gpt4 book ai didi

ruby-on-rails - ruby rails : link updates DB

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:19 25 4
gpt4 key购买 nike

简单的 RoR 问题...我正在学习 ROR 并正在制作一个简单的投票应用程序。候选人列在表格中,并且在他们的名字旁边有赞成/反对的链接。我试图做到这一点,所以用户所做的就是单击链接,更新投票计数,然后将他们重定向到初始页面。我没有使用脚手架。由于某种原因,此操作没有做任何接近我想要的事情:

def upvote
@name = Name.find(params[:id])
@name[:votes] += 1
respond_to do |format|
if @name.update_attributes(params[:name])
flash[:notice] = 'Candidate was upvoted'
format.html = { redirect_to :action => "index" }
format.xml = { head :ok }
else
format.html = { render :action => "index" }
format.xml = { render :xml => @name.errors, :status => :unprocessable_entity }
end
end
end

我在 View 中确实有调用正确操作的链接,不过它正在尝试调用 :show。

请不要对我评价太苛刻哈哈...

最佳答案

update_attributes 方法通常用于从表单 POST 设置 ActiveRecord 对象的字段。这些字段将作为散列 params[:name] 找到,例如params[:name][:votes].

如果您单击链接以调用 upvote 方法,那么您只是在执行 GET 请求。您需要做的就是调用 @name.save 来保存记录。

def upvote
@name = Name.find(params[:id])
@name[:votes] += 1
respond_to do |format|
if @name.save
flash[:notice] = 'Candidate was upvoted'
format.html = { redirect_to :action => "index" }
format.xml = { head :ok }
else
format.html = { render :action => "index" }
format.xml = { render :xml => @name.errors, :status => :unprocessable_entity }
end
end
end

编辑:根据评论,我们还确定路由设置不正确,并且 View 中的 link_to 代码需要包含 @name。编号

关于ruby-on-rails - ruby rails : link updates DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/838332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com