Rendering a partial from a controller in rails

后端 未结 1 1559
天涯浪人
天涯浪人 2020-12-16 14:31

I have a form that is adding rows to the DB via remote => true. I then want to append the new data to a table, but cannot get the correct view to render.

As of now,

相关标签:
1条回答
  • 2020-12-16 14:57

    Edited per the changes in your question. However, nothing really changes. You're thinking about things wrong, and need to adjust how you're thinking. You don't need an alternative show, you need to handle the format.js request.

    The partial should be rendered within a JavaScript response, not the controller. The controller looks more like this:

      def create
        @task = Task.new(params[:task])
    
        respond_to do |format|
          if @task.save
            format.html { redirect_to @task, notice: 'Task was successfully created.' }
            format.json { render json: @task, status: :created, location: @task }
            format.js
          else
            format.html { render action: "new" }
            format.json { render json: @task.errors, status: :unprocessable_entity }
            format.js
          end
        end
      end
    

    Then, in views/tasks/create.js.coffee

    ($ '#mytable').append("<%= j render(partial: 'tasks/newly_added', locals: { t: @task }) %>")
    

    What's going on here is that the browser makes a call to create.js. The controller responds with the create.js template, because of the respond_to block's format.js. The j escapes the contents of the _newly_added.html.erb file, and the contents of it are appended to the table. The controller doesn't interact with the existing view, instead, JavaScript is sent to the browser, and it interacts with the view.

    This all changes somewhat if you're using a client-side MVC framework like Backbone or Ember, but you didn't specify that so I'm assuming you're going with stock Rails.

    0 讨论(0)
提交回复
热议问题