Tag: activerecord

link_to与inheritance的Active Record类发生问题

以下是我设置的类: class Stat < ActiveRecord::Base belongs_to :stats_parent end class TotalStat < Stat belongs_to :stats_parent end #The StatsParent class is just to show how I use the relation. class StatsParent < ActiveRecord::Base has_one :total_stat has_many :stats end 对于统计控制器索引操作: def index @stats = Stat.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @stat } […]

Rails模型validation条件allow_nil?

所以我想知道我们是否可以在rails模型上使用条件allow_nil选项进行validation。 我想要做的是能够allow_nil取决于一些逻辑(一些其他属性) 所以我有一个产品型号可以保存为草稿。 当被保存为草案时,价格可以是零,但是当不是草稿时,保存价格应该是数字。 我该怎么做到这一点。 以下似乎不起作用。 它适用于草案,但即使状态不是草案也允许为零。 class Product<ActiveRecord::Base attr_accessible :status, price validates_numericality_of :price, allow_nil: :draft? def draft? self.status == "draft" end end 看看rails docs我看起来没有选项将方法传递给allow_nil? 一种可能的解决方案是对两种情况进行单独的validation with_options :unless => :draft? do |normal| normal.validates_numericality_of :price end with_options :if => :draft? do |draft| draft.validates_numericality_of :price, allow_nil: true end 任何其他方法来使这个工作? 谢谢

具有多个联接的ActiveRecord查询无法识别关系

我正在尝试编写一个ActiveRecord查询,该查询使用以下查询返回在特定课程中注册的所有学生: def self.students_enrolled_in(course_id) Student .joins(:enrollments) .joins(:sections) .joins(:courses) .where(sections: { course_id: course_id }) end rails控制台的结果是: ActiveRecord :: ConfigurationError:无法将’Student’加入名为’sections’的关联; 也许你拼错了吗? 这似乎是关联的结果。 我究竟做错了什么? 查询实际上是否意味着所有join()语句都必须与Student关联,或者是否应该跟踪关联链接? 教授节目页面: 楷模: 注册 class Enrollment < ApplicationRecord belongs_to :section belongs_to :student end 学生: class Student < ApplicationRecord has_many :enrollments end 教授: class Section (prof_id) { where(‘professor_id = ?’, prof_id) } end 课程: class Course […]

通过两个“has_many”子表的总和来排序查询?

在我的应用程序中, Invoice has_many item_numbers和Invoice has_many payments 。 每张发票都有一个余额,它是ItemNumber金额属性的总和,减去付款金额属性的总和。 在发票模型中很容易计算余额,但我正在尝试编写一个按余额对发票进行排序的查询,这在ActiveRecord / SQL中更难实现。 我已成功设法使用以下查询在item_numbers的总数上订购发票(感谢Daniel Rikowski): Invoice.where(user_id: 1, deleted: false, status: ‘Sent’) .joins(:item_numbers) .select(‘invoices.*, sum(item_numbers.amount)’) .group(‘invoices.id’) .order(‘sum(item_numbers.amount) asc’) .limit(20) 我试图通过下面的平衡来扩展这个顺序; Invoice.where(user_id: 1, deleted: false, status: ‘Sent’) .joins(:item_numbers) .joins(“FULL OUTER JOIN payments ON payments.invoice_id = invoices.id”) .select(“invoices.*, sum(item_numbers.amount_with_gst) – COALESCE(sum(payments.amount), 0)”) .group(“invoices.id”) .order(“sum(item_numbers.amount_with_gst) – COALESCE(sum(payments.amount), 0) #{dir}”)/ 此查询存在两个问题。 首先,它非常丑陋,其次,它不起作用。 […]

如何在创建ActiveRecord对象时设置属性?

我正在尝试在我正在创建的对象上设置属性。 我觉得这应该工作: def create @album = Album.new(params[:album]) @album.user = current_user if @album.save flash[:notice] = ‘Album was successfully created for ‘ + current_user.login + ‘.’ redirect_to albums_url else render :action => “new” end end 但似乎忽略了对user字段的分配。 有任何想法吗?

如果数据库为空,则处理ActiveRecord错误

我正在使用rails 4 app,我有以下控制器代码 def index @issue = Issue.find(1) @sections = @issue.sections @articles = @issue.articles end 如果数据库为空并且出现错误,则会中断:“无法找到id = 1的问题”。 检查这个问题的正确方法是什么,如果数据库中没有任何内容,它不会引发错误?

通过未保存的子关联访问父级(has_many)

我有一笔与每笔付款相关的交易付款。 交易可以与付款,存款等相关联,因此我需要:通过关系。 付款类: class Payment :payment_transactions end 和Transaction类: class Transaction :transaction has_one :payment, :through => :payment_transaction end 最后是PaymentTransaction类: class PaymentTransaction < ActiveRecord::Base belongs_to :payment belongs_to :transaction end 将交易添加到付款时,我希望能够从新创建的交易中访问父信息(付款属性): 2.1.0 :001 > p = Payment.new => # 2.1.0 :002 > p.save => true 2.1.0 :003 > p.transactions.build() => # 2.1.0 :004 > p.transactions.first.payment => nil 我正在寻找一种方法来从与支付相关的新创建的交易中获取付款 […]

显示消息数组中的最后一条消息

关于我上一次尝试的答案 ,我可以实现我想要的。 一旦应用程序正常工作,我发现有些不同之处:只有创建消息并发送消息的人才会显示。 如果我回复,我没有看到答复,我知道问题。 我的消息模型有表: [:id, :user_id, :to, :body, …] :user_id与用于确定创建消息的人类似。 User 1是客户端, User 2是学生。 学生向客户发送消息。 只有我的客户端代码是这样的: #Controller Index: @messages = Message.where(to: current_user.id) # My replies are not included here .order(user_id: :asc, created_at: :desc) .select(‘distinct on (user_id) *’) 我说给我发给我的所有消息( :to )id为1 。 由于:to列,我不会看到我的回复。 我的(客户端)回复如下所示: to: #student id user_id: #client id 和学生留言: to: #client id user_id: […]

嵌套关联/加入rails

我有一个seat对象,其car对象具有name的owner 。 我想一起展示car brand和car owner的name 。 如何在一个查询中执行此操作? 例如: class Seat how do I replace this with one query? end end 我会注意到这是一个非常人为的例子来简化我的问题。 我连续数千次这样做,因此需要更高的效率。

ActiveRecord:如果值无效,则中止datetime解析

我的ActiveRecord模型中有一个datetime字段(在Rails中),当date fieid超出范围时,我需要保护我的模型免于崩溃。 我发现了这个问题,并尝试做同样的事情 : class Something < ActiveRecord::Base validate :important_date_is_valid_datetime, on: :create validates :important_date, presence: true private def important_date_is_valid_datetime if (DateTime.parse(important_date.to_s()) rescue ArgumentError) == ArgumentError then errors.add(:important_date, 'must be a valid datetime') end end end 此代码可以“validation”datetime字段,但如果valie超出范围,则不会中止字段解析: irb(main):007:0> Something.new(important_date: “2015-20-40”).valid? ArgumentError: argument out of range from /home/shau-kote/.gem/ruby/2.1.0/gems/activesupport-4.2.0/lib/active_support/values/time_zone.rb:350:in `initialize’ from /home/shau-kote/.gem/ruby/2.1.0/gems/activesupport-4.2.0/lib/active_support/values/time_zone.rb:350:in `new’ from /home/shau-kote/.gem/ruby/2.1.0/gems/activesupport-4.2.0/lib/active_support/values/time_zone.rb:350:in `parse’ … 我可以防止类似的崩溃吗?