遍历数组以创建Rails对象 [英] Iterate through an array to create rails objects

查看:78
本文介绍了遍历数组以创建Rails对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到有关如何遍历数组和创建对象的任何信息。

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

我的表单创建了一个可选择的用户列表,该列表在选中后将user_ids作为数组对象传递。

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

invitations\new.html.rb

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 %>

然后我想通过将与会者的事件ID与与会者ID中的所有对象结合起来来创建新的邀请对象数组。

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.

在遇到一些麻烦之后,我掌握了控制器的基本功能,但仅通过将user_id作为文本输入传入即可。以下是我的邀请函控制器。由于我一直找不到很好的例子,因此不太确定从哪里开始。

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

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


推荐答案

您的意思是这样吗?

<%= 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

这篇关于遍历数组以创建Rails对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆