Is there a way to submit ajax/json requests with simple_form for Rails

后端 未结 5 1991
感情败类
感情败类 2021-01-05 09:43

With the standard Rails form_for, I was able to pass ajax requests though select and collection_select helpers as such:

<%= address.collection_select :cou         


        
5条回答
  •  一个人的身影
    2021-01-05 10:23

    The simplest way to do this that I have found, and for a fuller example, is:

    In your view:

    <%= simple_form_for :my_object, url: my_objects_path(format: :json), remote: true do |f| %>
      <%= f.error_notification %>
      <%= f.input :an_attribute %>
      <%= f.submit %>
    <% end %>
    

    and in your controller:

    def create
      @my_object = MyObject.new(my_object_params)
      if @my_object.save
        respond_to do |format|
          format.html { redirect_to @my_object, notice: "Saved" }
          format.json { render json: @my_object, location: my_object_url(@object), status: :created }
        end
      else
        respond_to do |format|
          format.html { render :edit }
          format.json {render json: @my_object, status: :unprocessable_entity }
        end
      end
    end
    

    In Rails 5 it's even easier on the controller with the Jbuilder installed to create simple json hashes but this should work there too.

提交回复
热议问题