Iterate through an array to create rails objects

2019-09-16 19:07发布

I am having trouble finding any information on how to iterate through an array and create objects.

My form creates a selectable list of users that when checked, pass the user_ids as an array object.

invitations\new.html.rb

<%= bootstrap_form_for Invitation.new do |f| %>
<br>
  <ul>
    <%= f.hidden_field :attended_event_id, :value => @event_selected.id %>
    <li>
    <%= check_box_tag 'attendee_id[]', user.id %>
    <%= h user.name %>
    </li>
    <% end %>
  </ul>
<br>
<%= f.submit "Invite Selected Users" %>
<% end %>

I would like to then create new Invitations objects by combining the attended_event_id with all of the objects in the attendee_id array.

After a bit of trouble I got the basics of my controller working but only by passing in the user_id as a text entry. Below is my Invitations controller. Not really sure where to start on this one as I haven't been able to find a good example.

invitations_controller.rb

  def create
     @invitation = Invitation.new(invite_params)

     if @invitation.save!
      flash.now[:success] = "Invited!"
       redirect_to root_path
     else
      flash.now[:error] = "Failure!"
      redirect_to root_path
     end
  end

  private
  def invite_params

    params.require(:invitation).permit(:attended_event_id, :attendee_id)
  end
end

3条回答
Fickle 薄情
2楼-- · 2019-09-16 19:44

Do you mean something like this?

<%= bootstrap_form_for Invitation.new do |f| %>
  <br>
    <ul>
      <%= f.hidden_field :attended_event_id, :value => @event_selected.id %>
      <% users.each do |user| %>
        <li>
          <%= check_box_tag 'invitation[attendee_id][]', user.id %>
          <%= h user.name %>
        </li>
      <% end %>
    </ul>
  <br>
  <%= f.submit "Invite Selected Users" %>
<% end %>


def create
@invitations = invite_params[:attendee_id].map do |attendee_id|
  Invitation.new(
    attended_event_id: invite_params[:attended_event_id],
    attendee_id: attendee_id
  )
end

if @invitations.any?(&:invalid?)
  flash.now[:error] = "Failure!"
  redirect_to root_path
else
  @invitations.each(&:save!)
  flash.now[:success] = "Invited!"
  redirect_to root_path
end
end

private
def invite_params
  params.require(:invitation).permit(:attended_event_id, {:attendee_id => []})
end
查看更多
beautiful°
3楼-- · 2019-09-16 19:47

Do you want to achieve something like this:

def create
  params[:attendee_id].each do |user_id|
    Invitation.create(:attended_event_id => params[:attended_event_id], :attendee_id => user_id)
  end
  .
  .
  .
end
查看更多
在下西门庆
4楼-- · 2019-09-16 19:53
登录 后发表回答