← Back to Upcase

Render modal from partial in controller?


(tehfailsafe ) #1

I am starting to move rather large nested if logic in a view to a decorator and trying to simplify my routes and controllers. I’m curious of a best way to build/launch a modal. To keep it simple, let’s say I have an attribute “first_post” on user so I can give some advice the first time the user creates a new post. I don’t want to have a hard-coded hidden modal in the view all the time that just changes css to display.

To get around that I currently (pre-decorator) have a custom route “check_user_attribute” which has an action on the user controller to do if/then, responding as ajax call from the view. I would much rather contain this bit of logic in one place instead of a new controller action (“check_attribute”) and route.

What I would like to happen is user clicks a button generated from the decorator to a create path, which checks to see if user has an attribute, if so render the warning modal, if not proceed to create action. Ultimately I’m trying to move this all to a new user_manager class, but trying to move in small steps.

Would simply using the user decorator to decide whether the users first post is true and calling it from the view work? something like ‘first_post?’ in the decorator that simply calls ‘render first_post_advice’ partial?


(Derek Prior) #2

It sounds like this is way more complicated than necessary. Could you conditionally render the first_post partial?

<% if current_user.first_post? %>
  <% render 'modal' %>
<% end %>

(tehfailsafe ) #3

Yes, perhaps I am over-thinking it…

However, wouldn’t I also need to put another conditional for the link_to tag? I don’t want to display the modal until the user actually clicks the button.

<% if current_user.first_post? %>
    <%= link_to "Create Post", new_user_post_path %>
<% else %>
   <%= link_to DISPLAY MODAL ?? %>
<% end %>

I’m new to OOP in general and decorators specifically, but I wanted to use the decorator pattern to remove the extra conditionals in the view.

Another option I was thinking of using ( maybe abusing? ) the remote option on the link_to helper.

<%= link_to "Create Post", new_user_post_path, remote: current_user.first_post? %>

then in the controller

def new
  if current_user.first_post?
    render 'post_advice_modal'
  else
    Post.create(post_params)
    redirect_to :back, notice: "Post created"
  end
end

Though then I’m duplicated the condtion twice as well. Is there a way to simplify it to just respond to remote with the render ‘partial’ and redirect_to for the non-remote call? Respond to format maybe? Never tried it like this.

Or am I way off base?