我正在寻找一种干净的方法来创建具有一组属性的记录(如果记录不存在)并且-如果记录存在-更新其属性。我喜欢find_or_create_by_id调用中block的语法。这是我的代码:@categories=Highrise::DealCategory.find(:all)@categories.eachdo|category|puts"Category:#{category.name}"Category.find_or_create_by_id(category.id)do|c|c.name=category.nameendend这里的问题是,如果记录存在但名称已更改,则不会更新。正在
您好,我已经搜索过了,但还没有找到执行此操作的方法我有以下模型:classHierarchy.classFamily:hierarchiesend.classUser:hierarchiesend有了current_user,我需要获取他的所有其他家庭成员,按级别分组,然后按列顺序排序。我会说出我尝试过的,但实际上并没有那么多,而且这个查询超出了我的能力范围。我正在使用postgres。 最佳答案 我会采用以下方法..我们必须更新用户模型:)classUser:hierarchieshas_many:family_members,-
我有两个模型:User和Message,它们通过has_many关系连接。我想获得一个users列表,按他们上一条消息的时间戳排序。classUser当我这样做时:@users=User.includes(:messages).order('messages.created_atDESC').limit(5)它似乎对消息进行排序,获取最新的5条消息,然后返回与这些消息关联的用户。所以用户数可以少于5个。我想确保获得5个用户。我希望查询为每个请求获取最新消息,对最后的消息进行排序,然后将最新消息返回给用户。所以我想要这样的东西:@users=User.includes(:messages
所以我知道Rails在像这样使用时有助于防止sql注入(inject):Object.find(:first,:conditions=>["name=?",name])但是,我似乎无法确定自动生成的find_by和find_all_by方法是否可以防止sql注入(inject)。即:Object.find_by_name(name)因此这两个调用具有完全相同的结果。我的问题是,即使第二个更方便,我是否应该继续使用第一个,因为它提供了针对sql注入(inject)的保护,还是第二个也这样做? 最佳答案 是的,基于动态属性的查找器(fi
在ActiveRecord/RubyonRails中执行此查询的最佳方式是什么SELECTsum(amount)作为total_amountFROMpaymentsGROUPBYperson_id,product_id我似乎无法将sum与group方法链接起来。我必须在这里求助于find_by_sql吗? 最佳答案 类似于:Payment.group(:person_id).group(:product_id).sum(:amount)应该给你一个散列,其键是[person_id,product_id]数组,其值是总和。您可能不想:
我正在尝试创建一个已发表评论的唯一患者列表。代码字很好,直到我上传到heroku,它在postgresql中不起作用。这是我创建列表的Ruby.erb代码:Lastestcommentfromago@comments在Controller中定义为:defindex@comments=current_clinician.comments.order("created_atdesc")endheroku日志给我这个错误信息:PG::GroupingError:ERROR:column"comments.id"mustappearintheGROUPBYclauseorbeusedinana
如何重写这段代码,使其完全动态,并且不必使用case子句手动列出@group的所有可能值?#Grouping@group=params[:group]if!params[:group].blank?case@groupwhen'category_id'@ideas_grouped=@ideas.group_by{|i|i.category_id}when'status_id'@ideas_grouped=@ideas.group_by{|i|i.status_id}when'personal_bias'@ideas_grouped=@ideas.group_by{|i|i.person
我想向我的Controller提交一个产品ID和一个零售商ID,如果数据库中存在该组合,我想用提交的参数更新该记录,如果不存在,则创建一个新记录。我的Controller在下面,目前我可以看到,如果组合不存在,则会创建记录,但是当找到组合时,它会执行选择查询并且不会更新记录。我怎样才能让它更新而不只是选择?谢谢Controller:defAddNewPrice@newPrice=ProductPrice.find_or_create_by(product_id:params[:product_id],retailer_id:params[:retailer_id])end更新抱歉..刚
我正在使用这种方法:defself.lines_price_report(n)Income.group('date(filled_at)').having("date(filled_at)>?",Date.today-n).sum(:lines_price)end我在Heroku中遇到这个错误:PG::Error:ERROR:column"incomes.filled_at"mustappearintheGROUPBYclauseorbeusedinanaggregatefunction我该如何解决这个问题?谢谢。执行的查询:SELECTSUM("incomes"."lines_pri
有没有办法重写下面的流程,目前使用find_or_initialize_by,使用joins方法?对于上下文-我有users(员工)在系统中记录他们的attendances(user有很多attendances,考勤记录属于用户)。Attendance.find_or_initialize_by(user:User.find_by(name:'Bob'),date:Time.zone.today).update(...)#Updatesomecolumnsafterthis我正在尝试使用.joins重写它,如下所示:Attendance.joins(:user).where(users