简体   繁体   中英

Updating Div in Rails without changing view after an update request

I'm new to rails. I'm using form_for to update a 'collab' database entry. I've modified my update function to create a new instance variable called "@interpreted_code" and assigned it to a string. When this variable is created/changed in my update function I'd like the view to display it without a reload. Here is my view, collab.html.erb

<%= form_for @collab, :remote=>true do |f| %>

  <p>
    Enter Ruby Code<br>
    <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>

<% end %>

<div id='interpreted' > 
  <%= @interpreted_code.inspect %> #this doesn't work
</div>

And here is my update function in my controller.rb

def update
    @collab = Collab.find(params[:id])

    if @collab.update(collab_params)
      File.open('rubyfile.rb', 'w') { |file| file.write(@collab.text) }
      @interpreted_code = "BLAH BLAH (change later)"
    end

    render :nothing =>true
  end

Try this-

First create a partial like this _interpreted_code.html.erb

<%= @interpreted_code.inspect %>

Change your view now like this-

<%= form_for @collab, :remote=>true do |f| %>
  <p>
   Enter Ruby Code<br>
   <%= f.text_area :text %>
  </p>

  <p>
    <%= f.submit %>
  </p>
<% end %>

<div id='interpreted' > 
  <%= render partial: "interpreted_code" %> 
</div>

Create file update.js.erb

$("#interpreted").html("<%= raw escape_javascript(render(:partial => 'interpreted_code')) %>")

Change your controller like this-

def update
 @collab = Collab.find(params[:id])

 if @collab.update(collab_params)
   File.open('rubyfile.rb', 'w') { |file| file.write(@collab.text) }
   @interpreted_code = "BLAH BLAH (change later)"
 end

 respond_to do |format|
   format.js
 end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM