简体   繁体   中英

Is it possible to render partial onclick without link_to?

I was wondering if it's possible to render partial onclick without link_to ?

I have been searching for answers but most of the answers state that using link_to and blabla_path with remote: true but I don't want to handle it through controller, instead just the views side.

Something like

<%= if button.click? render "form" %> <%= if button.click? render "form" %> <--(this obviously won't work but something like this)

Thanks

By the way, I am using Rails 4.0.1

====

Update

I have tried it dynamically, using ajax and jquery, it's works but it's weird. Please see below my code, I've placed the link inside a loop but when the "New Comment" is clicked, it appear on the first post, when I clicked the "New Comment" on the second/third/fourth all of the partials got render on the first post. What is going on? When I click "New Comment" on the second post, it should appear on the second post instead of the first one.

<% @posts.each do |post| %>

   <%= post.title %>

   <%= post.content %>

   <%= link_to 'New Comment', new_comment_path, id: 'new_comment', remote: true %>

<% end %>

If you really want to fetch the view dynamically on clicking a link or button you have to go through by controller. AS Per MVC rule. But in your case you can try something like on loading the page render the partial and make it hidden. and on clicking a button or link just remove its hidden property through jQuery or javascript .

Simple

Sabyashachi Ghosh is spot on about keeping elements hidden in the DOM, so you can unhide them on click. Although highly inefficient, it will achieve exactly what you desire


Dynamic

You'll have to use Ajax & a controller action to handle the request

The only way to dynamically load something from Rails is to send a request. Rails is like a giant API -- you have to send your requests to a series of endpoints (routes), which Rails then handles with a controller

Your problem is you'll only be able to load something dynamically if you have the required routes in place to send the request through to a specific controller action, which will then handle the request & allow Rails to render the result

I'd do this:

#app/controllers/application_controller.rb
Class ApplicationController < ActionController::Base
    layout Proc.new {|controller| controller.request.xhr? false : "application" } #-> sets layout to false for ajax requests
end

#view
<%= link_to "Load Popup", action_path, remote: :true %>

#javascript
$("a[data-remote=true]").on("ajax:success", function(data) {
    //handle data
});

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