Skip to content

Commit 2e914ff

Browse files
committed
Refactor event_host build logic to clean up setting something as the event host.
Ensures that the host record is in scope and accessible to the person before assigning it as a host.
1 parent b56e456 commit 2e914ff

File tree

2 files changed

+25
-13
lines changed

2 files changed

+25
-13
lines changed

app/controllers/better_together/events_controller.rb

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,32 @@ class EventsController < FriendlyResourceController
88
Rails.application.eager_load!
99
end
1010

11+
before_action :build_event_hosts, only: :new
12+
1113
def index
1214
@draft_events = @events.draft
1315
@upcoming_events = @events.upcoming
1416
@past_events = @events.past
1517
end
1618

17-
def new
18-
@host_id = params[:host_id]
19-
@host_type = params[:host_type]
20-
super
21-
end
22-
2319
protected
2420

21+
def build_event_hosts
22+
return unless params[:host_id].present? && params[:host_type].present?
23+
24+
host_klass = params[:host_type].safe_constantize
25+
return unless host_klass
26+
27+
policy_scope = Pundit.policy_scope!(current_user, host_klass)
28+
host_record = policy_scope.find_by(id: params[:host_id])
29+
return unless host_record
30+
31+
resource_instance.event_hosts.build(
32+
host_id: params[:host_id],
33+
host_type: params[:host_type]
34+
)
35+
end
36+
2537
def resource_class
2638
::BetterTogether::Event
2739
end

app/views/better_together/events/_form.html.erb

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
<%= form_with(model: event, class: 'form', multipart: true, id: dom_id(event, 'form'), local: true, data: { controller: "better_together--form-validation better_together--tabs" }) do |form| %>
2-
<% if host_id.present? && host_type.present? %>
3-
<%= form.fields_for(:event_hosts, (form.object.event_hosts.build(host_id:, host_type:))) do |event_host_fields| %>
4-
<%= event_host_fields.hidden_field :host_id %>
5-
<%= event_host_fields.hidden_field :host_type %>
6-
<% end %>
7-
<% end %>
8-
<%= form.hidden_field :creator_id, value: current_person&.id unless form.object.creator_id %>
2+
<%= form.fields_for(:event_hosts) do |event_host_fields| %>
3+
<%= event_host_fields.hidden_field :host_id %>
4+
<%= event_host_fields.hidden_field :host_type %>
5+
<% end %>
6+
7+
<%= form.hidden_field :creator_id, value: current_person&.id unless form.object.creator_id %>
8+
99
<% content_for :resource_toolbar do %>
1010
<div class="btn-toolbar mb-3" role="toolbar" aria-label="<%= t('helpers.toolbar.aria_label') %>">
1111
<div class="btn-group me-2" role="group">

0 commit comments

Comments
 (0)