【问题标题】:Passing a string to an object in controller using ajax使用ajax将字符串传递给控制器​​中的对象
【发布时间】:2015-12-01 22:14:41
【问题描述】:

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

在我的程序中,我得到的用户输入包含一个新展位的管理员,该展位是通过我的 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关联,其中join表称为BoothUser,其中包含booth_id, user_id, is_admin的信息,其中id是特定用户和Booth在各自表中的索引, is_admin 是一个布尔值,用于检查用户是否是展台的管理员(具有编辑展台设置的权限)。

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

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

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

所以,我想问有没有办法这样做,如果有,我该怎么做?还是只是不允许?

【问题讨论】:

    标签: javascript ruby-on-rails ruby ajax ruby-on-rails-4.2


    【解决方案1】:

    你应该可以这样创建它:

    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")
            }
        }); 
    });
    

    【讨论】:

    • 哦,对不起...我想我还没有明确表示没有任何东西传递给控制器​​,所以当我尝试使用收到的电子邮件向 BoothUser 表添加新条目时,:booth_admin_emails该字段为空,因此不会将任何内容复制到@booth_admins 和booth_admins....您是否知道为什么不会将任何内容传递给该字段?
    • 我明白了。问题似乎是您的 HTML 和控制器不一致。我会更新我的答案。
    • 您的文本区域中缺少名称属性,因此它不会与您的表单一起提交。
    • 非常感谢!现在可以了!但是您能否解释一下以这种格式命名的名称如何允许将输入传递到booth_admin_emails 字段?再说一次,我开始学习网络编程,所以到目前为止我对该语言的理解非常低;(
    • 首先,textarea 就像任何其他输入一样,需要一个名称。是提交的“键值对”中的“键”。没有名字就不会提交。其次,Rails 将参数嵌套到一个类似哈希的键值对数组中。因此,在您的控制器中,您会看到类似params[:user][:first_name]params[:user][:last_name] 的内容。在 HTML 中,要提交该结构,我们需要适当地命名输入:user[first_name]user[last_name]form_for 已经构建了大部分结构。添加其他自定义字段需要了解这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多