我在Rails的模型中有这个功能,我假装做的是它返回两个未删除的第一类和一些文章,但是当我运行应用程序时,它给了我这个错误
/Users/juampi/Desktop/iaw2015/app/models/category.rb:14: syntax error, unexpected keyword_end end ^
/Users/juampi/Desktop/iaw2015/app/models/category.rb:16:语法错误,意外的keyword_end结束^
这是模型category.rb
class Category < ActiveRecord::Base
has_many :articles, dependent: :destroy
validates_uniqueness_of :nombre
def PrimerasDosNoVacias
cant=0
aux =0
cate=["",""]
categorias = Category.where(eliminado: false)
while (categorias.length >= aux && cant < 2)
if (Article.where(category_id: categorias[aux].id).length != 0)
cate=categorias[aux]
cant++
end
aux++
end
end
end
我调用方法的视图
.. <% categories = Category.PrimerasDosNoVacias %> ..
答案 0 :(得分:2)
Ruby不支持++
运算符。
将其更改为+=1
class Category < ActiveRecord::Base
has_many :articles, dependent: :destroy
validates_uniqueness_of :nombre
def PrimerasDosNoVacias
cant=0
aux =0
cate=["",""]
categorias = Category.where(eliminado: false)
while (categorias.length >= aux && cant < 2)
if (Article.where(category_id: categorias[aux].id).length != 0)
cate=categorias[aux]
cant+=1
end
aux+=1
end
end
end
Why doesn't Ruby support i++ or i-- (increment/decrement operators)?
答案 1 :(得分:0)
您的while
缺少do
:
while (categorias.length >= aux && cant < 2) do
答案 2 :(得分:0)
Ruby没有++
运算符。而不是做例如cant++
,cant += 1
:
if (Article.where(category_id: categorias[aux].id).length != 0)
cate = categorias[aux]
cant += 1
end
aux += 1
答案 3 :(得分:0)
问题是调用Category.PrimerasDosNoVacias
,因为你直接调用它应该是Class
方法的类,因此请尝试: -
class Category < ActiveRecord::Base
has_many :articles, dependent: :destroy
validates_uniqueness_of :nombre
class << self
def PrimerasDosNoVacias
cant=0
aux =0
cate=["",""]
categorias = Category.where(eliminado: false)
while (categorias.length >= aux && cant < 2)
if (Article.where(category_id: categorias[aux].id).length != 0)
cate=categorias[aux]
cant+=1
end
aux+=1
end
end
end
end