简体   繁体   中英

Rails: How to render partial view from another controller

I am making a reddit clone. Right now I have a voting system that works, but it refreshes the page each time a user votes. I want to make this async by using AJAX.

Making buttons respond to Jquery is really hard though because they change state depending on how a user has voted on a post. The solution I came up with is this: Have 2 upvote buttons in the _upvote partial, and have 2 downvote buttons in the _downvote partial. Each partial will have one voting button that is activated when the case is already true, and clicking on it again will destroy it (for example, if a post is already upvoted on, then reclicking the upvote button will destroy it). The other button(s) in the partial will be activated in the case that the button has not been used yet (in which case clicking the button will create it).

Example: ****The _upvote partial should have the following buttons in it:****

1)create_upvote

2)destroy_upvote

****The downvote partial should have the following buttons in it:****

1)create_downvote

2)destroy_downvote

Whichever buttons are activated will depend on the controller.

My question(s) are this:

1) What is the actual syntax to a render partial view from another controller? For example: posts is rendering _post, and within that I want _upvote or _downvote to be rendered. How to render _upvote or _downvote from the controller. Again, the reason I WANT to render these partials from a controller is because the controller will be changing their state.

Downvotes partial

app/views/posts/_downvote.html.erb

_downvotes 部分

Upvotes partial

app/views/posts/_downvote.html.erb

_upvotes 部分

Posts partial

app/views/posts/_post.html.erb

_post 部分

Downvotes controller

反对票控制器

Upvotes controller

点赞控制器

Line 9 in the controllers is where my syntax is off! What is the syntax to render _upvote and _downvote partials, within the _posts partial? Thanks mates!

As far as syntax goes, what you want is the following:

render partial: "posts/upvote"

Instead of sending html data (the buttons you mentioned) from controller to the partial, you should have a conditional statement in each partial that activates one button or another. From there create event handlers for each respective button. That takes care of the issue of Jquery handling internal state.

Just a small note for the special cast of partials inside views/layouts/_upvote.html.erb , you should use

render partial: "layouts/upvote"

(not application/upvote )

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