我对ruby-on-rails非常新,希望你能帮助我。我正在尝试使用ruby-on-rails为Redmine编写一个插件。而且我在控制器中从我的模型中调用一个新方法时遇到了一些问题。所以我制作了Redmine插件教程并在之后有了这些项目:
型号:
class Poll < ActiveRecord::Base
def vote(answer)
increment(answer == 'yes' ? :yes : :no)
end
end
控制器:
class PollsController < ApplicationController
def index
@project = Project.find(params[:project_id])
@polls = Poll.all
end
def vote
poll = Poll.find(params[:id])
poll.vote(params[:answer])
if poll.save
flash[:notice] = 'Vote saved.'
end
redirect_to :action => 'index'
end
end
的index.html:
<h2>Polls</h2>
<% @polls.each do |poll| %>
<p>
<%= poll.question %>?
<%= link_to 'Yes', { :action => 'vote', :id => poll[:id], :answer => 'yes' }, :method => :post %> (<%= poll.yes %>) /
<%= link_to 'No', { :action => 'vote', :id => poll[:id], :answer => 'no' }, :method => :post %> (<%= poll.no %>)
</p>
<% end %>
之后我想将Wikicontent添加到同一个html中,以便习惯使用RoR。所以我现在的项目看起来像这样:
型号:
class Poll < ActiveRecord::Base
def vote(answer)
increment(answer == 'yes' ? :yes : :no)
end
def self.load_content
@wiki_content = Poll.find_by_sql ("select wc.text
, wc.comments
, wc.version
from wiki_contents wc
where wc.page_id = (select min(id)
from wiki_pages
where wiki_id = 3")
end
end
控制器:
class PollsController < ApplicationController
def index
@project = Project.find(params[:project_id])
@polls = Poll.all
@wiki_content = Poll.load_content
end
def vote
poll = Poll.find(params[:id])
poll.vote(params[:answer])
if poll.save
flash[:notice] = 'Vote saved.'
end
redirect_to :action => 'index'
end
end
的index.html:
<h2>Polls</h2>
<% @polls.each do |poll| %>
<p>
<%= poll.question %>?
<%= link_to 'Yes', { :action => 'vote', :id => poll[:id], :answer => 'yes' }, :method => :post %> (<%= poll.yes %>) /
<%= link_to 'No', { :action => 'vote', :id => poll[:id], :answer => 'no' }, :method => :post %> (<%= poll.no %>)
</p>
<% end %>
<% @content.each do |cn| %>
<p>
<%= cn.text %>
</p>
<% end %>
根据我的浏览器,我得到了“内部错误”。我试图找到错误,似乎我无法从控制器内部的模型中调用新方法,我无法弄清楚原因。就像我说的那样,我对RoR很新,所以我希望你能帮助我。
这是日志文件中的错误描述:
ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 7: select wc.text
, wc.comments
, wc.version
from wiki_contents wc
where wc.page_id = (select min(id)
from wiki_pages
where wiki_id = 3):
最诚挚的问候 附庸风雅
答案 0 :(得分:1)
您需要在模型方法中返回一些内容,而不是将值赋给@wiki_content
,因为模型对该变量没有任何可见性
看起来像那样
def self.load_content
return Poll.find_by_sql ("select wc.text
, wc.comments
, wc.version
from wiki_contents wc
where wc.page_id = (select min(id)
from wiki_pages
where wiki_id = 3")
end
答案 1 :(得分:1)
在您使用index.html
的{{1}}中,但在您的代码段中没有任何地方为<% @content.each do |cn| %>
分配任何值。由于您在控制器@content
操作中分配@wiki_content
,我假设您要在此处使用index
:
@wiki_content
<强>更新强>
根据您发布的错误并仔细查看您的查询,您的查询中出现语法错误。您缺少内部选择中的右括号# app/views/polls/index.html
...
<% @wiki_content.each do |cn| %>
<p>
<%= cn.text %>
</p>
<% end %>
。更新您的查询,如下所示:
)