使用 ajax 将字符串传递给控制器​​中的对象

Passing a string to an object in controller using ajax

我是网络编程新手。所以我在网上搜索了一段时间自己解决了这个问题,但似乎没有人有类似的问题。

在我的程序中,我收到的用户输入包含新展台的管理员,该展台是通过我的 app/views/booths/new.html.erb 文件中的文本区域创建的,如下所示。

app/views/booths/new.html.erb :

<% provide(:title, 'Create New Booth') %>
<h1>Create New Booth</h1>

<% javascript_include_tag "booths" %>

<div>
  <div>
    <%= form_for(@booth) do |f| %>
      <%= f.label :booth_name, "Name of the new Booth" %>
      <%= f.text_field :booth_name %>

      <%= f.label :booth_description, "Describe your new Booth" %>
      <%= f.text_field :booth_description %>

      <%= f.label :important_notice, "Any important notices?" %>
      <%= f.text_field :important_notice %>

      <span><br>Admins for this Booth?<br> </span>
      <textarea id="create_booth_admins_textarea" rows="30" cols="50"> </textarea>

      <%= f.submit "Create a new booth", :id => "booth_create_submit"%>
    <% end %>
  </div>
</div>

app/assets/javascripts/booths.js 摘录:

admins = $("textarea#create_booth_admins_textarea").val();

$('#booth_create_submit').click(function() {
    $.ajax({
        url: "/booths_create",
        data: {  "booth_admin_emails" : admins},
        type: "post",
        cache: false,
        success: function () {
            console.log("ajax successful");
            alert("ajax successful");
        },
        error: fucntion() {
            console.log("ajax error");
            alert("ajax error")
        }
    }); 
});

app/controller/booths_controller.rb :

def new
        @booth = Booth.new
        @other_members = []
        @booth_admins = []
    end

    def create
        temp_hash = booth_params
        @booth = Booth.new(temp_hash.except(:booth_admin_emails))
        @booth.admin_id = current_user.id               #fill in the Booth table

        @booth_admins = temp_hash[:booth_admin_emails]

        booth_admins = []

        if @booth.save
            #fill in join table
            BoothUser.create(:user_id => current_user.id, :booth_id => @booth.id, :is_admin => true) #add current user

            if !@booth_admins.nil?
                booth_admins = @booth_admins.split(",")
            end

            if !booth_admins.empty?
                booth_admins.each do |email|
                    BoothUser.create(:user_id => User.where("email=?", email).id, :booth_id => @booth.id, :is_admin => true)
                end
            end

            # just a flash to tell user that new booth was created
            name = @booth.booth_name
            flash[:success] = "New Booth #{name} created!"
            redirect_to '/booths'
        else
          render('show')
        end
    end

    private
    def booth_params
        params.require(:booth).permit(:booth_name, :booth_description, :important_notice, :booth_admin_emails)
    end

User和Booth属于has_many through关联,其中jointable称为BoothUser,其中包含booth_id, user_id, is_admin的信息,其中id为索引特定用户及其各自 table 和 is_admin 中的展位是一个布尔值,用于检查用户是否是展位的管理员(具有编辑展位设置的权限)。

出现问题是因为在我的展位 table 中,我只声明了展位的创建者,并没有跟踪该展位的给定管理员,而是试图通过查找来找到该展位的这些管理员向上连接 table,其中 booth_id 与该展位的索引匹配并且 is_admin 为真。

我一直在尝试将 create_booth_admins_textarea 上输入的内容传递给控制器​​中的 :booth_admin_emails,但到目前为止运气不佳,因为没有任何内容传递到 :booth_admin_emails。我猜这是因为 :booth_admin_emails 不是 BoothUserBoothUser 模型的属性。

我在网上找到的是使用强参数(?)传递参数的方法,以允许使用 form_for 或 ajax 的模型属性。但是似乎没有人将不是模型属性的输入传递给控制器​​。

所以,我想问问有没有办法做到这一点,如果有,我该怎么做?或者只是不允许?

您应该可以像这样创建它:

BoothUser.create(user: current_user, booth: @booth, is_admin: true) #add current user
booth_admins.each do |email|
  admin = User.find_by(email: email)
  BoothUser.create(user: admin, booth: @booth, is_admin: true)
end

在您的 HTML 中,您需要像这样创建文本区域:

<textarea id="create_booth_admins_textarea" name="booth[booth_admin_emails]" rows="30" cols="50"> </textarea>

那你根本不需要JavaScript。

...但是,如果您希望通过 AJAX 提交整个表单,那么除了上面的 HTML 更改之外,在您的 JavaScript 中执行此操作:

$('#booth_create_submit').click(function(e) {
    e.preventDefault(); # keeps the HTML form from submitting.
    var the_form = $(this.form);
    $.ajax({
        url: the_form.attr('action'),
        data: the_form.serialize(),
        type: "post",
        cache: false,
        success: function () {
            console.log("ajax successful");
            alert("ajax successful");
        },
        error: fucntion() {
            console.log("ajax error");
            alert("ajax error")
        }
    }); 
});