ohnu93
ohnu93

Reputation: 273

Passing a string to an object in controller using ajax

I'm new to web programming. So I've been searching on the web for awhile to solve this on my own, but there seems to be no one who has similar problems.

In my program, I am getting user input that contains the admins for a new booth that's being created through a textarea in my app/views/booths/new.html.erb file, as shown below.

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 excerpt:

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 and Booth are of has_many through association, where the join table is called BoothUser, which contains information of the booth_id, user_id, is_admin, where the id are the indicies of the specific user and the booth in their respective tables and is_admin is a boolean value checking whether the user is an admin (has the permission to edit booth settings) of the booth.

The problem arises because in my Booth table, I only declare the creator of the booth, and do not track the given admins for that booth, but am trying to find these admins for that booth by looking up the join table where the booth_id matches the index of that booth and is_admin is true.

I have been trying to pass what's being input on the create_booth_admins_textarea to :booth_admin_emails in the controller but so far had no luck, as nothing was passed onto the :booth_admin_emails. I'm guessing it's because :booth_admin_emails is not an attribute of Booth or User or BoothUser model.

And what I found on web are ways to pass arguments using strong parameters(?) to permit an attribute of a model using form_for or ajax. But no one seems to have passed input that is not an attribute of a model to the controller.

So, I wanted to ask is there a way to do so and if there is, how do I do it? Or is it just not allowed?

Upvotes: 1

Views: 60

Answers (1)

Karl Wilbur
Karl Wilbur

Reputation: 6187

You should be able to create it like this:

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

In your HTML, you need to create your textarea like this:

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

Then you don't need the JavaScript at all.

...however if you want the entire form to submit via AJAX, then in addition to the HTML changes above, in your JavaScript do this:

$('#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")
        }
    }); 
});

Upvotes: 1

Related Questions