我需要使用查询的结果,发现使用表单参数查询另一个表,我遇到了困难。
第一个查询是:
@criteria_event = CriteriaEvent.joins(:events).where("events.horse_id = ? AND events.task_group_id = ? AND events.start_date = ?", criteria_event_params[:horse_id], criteria_event_params[:task_group_id], criteria_event_params[:start_date])
此查询返回正确的信息如下:
[#<CriteriaEvent id: 57, task_group_id: 3, start_time: "2000-01-01 10:00:00", created_at: "2016-02-12 01:36:54", updated_at: "2016-02-12 01:36:54", start_date: "2016-02-23", horse_id: 13>]>
我一直在尝试使用 CriteriaEvent id: found above (id:57) 在以下查询中返回相关事件。此查询紧跟在上述查询之后:
@events = Event.where(criteria_event_id: @criteria_event.id)
我收到以下错误:
NoMethodError (undefined method `id' for #<CriteriaEvent::ActiveRecord_Relation:
相关模型有以下几种:
class CriteriaEvent < ActiveRecord::Base
has_many :events
accepts_nested_attributes_for :events
end
class Event < ActiveRecord::Base
belongs_to :criteria_event
end
Controller 具有以下权限:
def criteria_event_params
params.require(:criteria_event).permit(:horse_id, :task_group_id, :start_date, :start_time, events_attributes: [:id, :criteria_event_id])
end
def event_params
params.require(:event).permit(:title, :start_date, :start_time, :end_date, :end_time, :location, :description, :notification_type, :notification_span_before, :notification_span_type, :horse_id, :task_group_id, :criteria_event_id, criteria_events_attributes: [:criteria_event_id, :id])
end
我错过了什么?
提前感谢您的帮助
最佳答案
嘿,你正试图在事件记录关系上选择 id
你可以使用 map
作为 id
的数组,
@events = Event.where(criteria_event_id: @criteria_event.map(&:id))
您可以通过这种方式找到事件,而不是使用单独的查询,
@events= Event.joins(:criteria_event).where("events.horse_id = ? AND events.task_group_id = ? AND events.start_date = ?", criteria_event_params[:horse_id], criteria_event_params[:task_group_id], criteria_event_params[:start_date])
关于mysql - 如何使用使用表单参数找到的一个表的结果来查询另一个表 - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35403755/