Link_to_post - Is this a good idea?

I’m using the CRUD pattern for my domain model to get RESTful stuff for
free. As such, I’ve got Users, Groups, and Membership models. I’m
creating the UI for adding and removing users from groups. I want to
click a user’s name and toggle them as included/excluded from a group.
With CRUD this means creating and destroying Membership objects.

For deleting, this wasn’t a problem. I could write something like:

<%= link_to ‘Delete’, membership_path(membership), :confirm=>‘Are you
sure’, :method=>:delete %>

And get exactly what I wanted. However, I couldn’t figure out any way
to create Membership objects as easily. Ideally it’d be something like

<%= link_to, memberships_path, :membership=>{:group=>group,
:user=>user}, :method=>:post %>

But I couldn’t figure out any way to pass params when :method=>:post.
Is there a way to do this?

My quick solution is to create a new method called link_to_post. Right
now it looks like this:

def link_to_post(anchor, path, *args)
link = “<a href=”#{path}" \n"
link = link + “onclick=“var f = document.createElement(‘form’); \n”
link = link + “ = ‘none’; \n”
options = args.last.is_a?(Hash) ? args.pop : {}
options.each do |option|
var = option.first
var = var.gsub(’[’, ‘’)
var = var.gsub(’]’, '
if option.last.is_a?(Hash)
# place holder - want to implement arbitrary hashes of hashes
link = link + “var #{var} = document.createElement(‘input’); \n”
link = link + “#{var}.name = ‘#{option.first}’; \n”
link = link + “#{var}.type = ‘text’; \n”
link = link + “#{var}.value = ‘#{option.last.to_param}’; \n”
link = link + “f.appendChild(#{var}); \n”
link = link + “this.parentNode.appendChild(f); \n”
link = link + “f.method = ‘POST’; \n”
link = link + “f.action = this.href; \n”
link = link + “f.submit(); \n”
link = link + “return false;”>#{anchor}”

It’s far from perfect. It can’t take in arbitrary hashes and the
Javascript variable naming isn’t pretty. Right now I’m calling it with:

<%= link_to_post, memberships_path,
‘membership[group_id]’=>group, ‘membership[user_id]’=>user %>

Ideally I’d like to see the regular link_to with :method=>:post take in
parameters, but is this a good idea? Should I write this as a Rails bug
fix or just keep using link_to_post for myself?

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs