Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a parameter to a form partial that is shown via CSS?

So my form partial is loaded in my div id="secondary", which is hidden on first page load.

When the user hits a button with a class called toggleSidebar, then the _form.html.erb is shown.

I have overridden the partial to display a new form (even if update is pressed) when a user is not logged in like this:

<%= simple_form_for(Post.new, html: {class: 'form-horizontal' }) do |f| %>  

As opposed to the regular version that looks like this, and is included in an if statement on this same partial:

<% if current_user and current_user.has_any_role? :editor, :admin %>
    <%= simple_form_for(@post, html: {class: 'form-horizontal' }) do |f| %> 

The real issue is in my view, when someone goes to Update, this is what happens when the user is logged out:

 <%= link_to "Update", "#", class: "togglesidebar" %>

This is perfect, it executes the CSS and shows the empty form partial perfectly.

However, when a user is logged in, I want it to send the parameter parent_id: @post with the execution of the sidebar being toggled.

This is how it looks with a normal new_post_path view (i.e. the non-sidebar new post view):

<% if current_user %>                                    
     <%= link_to "Update", new_post_path(parent_id: @post) %>
<% end %>

This is what my PostController#New looks like:

  def new
    @post = Post.new(parent_id: params[:parent_id])
  end

How do I either pass the params in the regular non new_post_path version, or tackle this another way?

like image 512
marcamillion Avatar asked Nov 27 '14 10:11

marcamillion


2 Answers

You could probably use a helper method.

Just browse to the 'helper' directory under 'app' folder and create a file similar to [name]_helper.rb

In this file create a module by [name]Helper and declare your helper method in this module.

This module is automatically required by rails.

A small example might help you.

The code in the link_helper.rb under app/helper directory

module LinkHelper

  def populate_link(link1, link2, parameter)
    if current_user
      public_send(link2, parameter)
    else
      link1
    end
  end

end

The code in views is

<%= link_to 'update', populate_link('#', 'new_requirement_path',parameter: 33) %>
like image 137
jaspreet21anand Avatar answered Sep 21 '22 02:09

jaspreet21anand


I'm a bit confused by the question, but I think you may be just need to use a hidden field to pass the parent_id param back?

e.g./

<%= simple_form_for(Post.new, html: {class: 'form-horizontal' }) do |f| %> 
  <%= f.hidden_field :parent_id, { value: @post.try(:id) } %>
<% end %>

HTH?

like image 37
gef Avatar answered Sep 21 '22 02:09

gef