Note that there are some explanatory texts on larger screens.

plurals
  1. PORails3: Is there a best practice for updating attributes without a form?
    text
    copied!<p>I've been stuck on this for a few days and I'm afraid I lack the vocabulary to properly ask this question, but any feedback is greatly appreciated!</p> <p>I am working on a basic blog site. Users can create posts with a title, description, and declare whether others can see the post (public or private). From the index page, I want the user to be able to see a list of their posts, toggle public|private, and delete the post. Listing is easy (I'm rendering a partial based on the user's posts), and the AJAX delete link is working nicely:</p> <pre><code>&lt;%= link_to 'Delete Post', post, :confirm =&gt; 'Are you sure?', :method =&gt; :delete, :remote =&gt; true %&gt; </code></pre> <p>Toggling public|private corresponds to an edit/update action, and I cannot figure out how to do that using a link or button--it seems I have to use a form. I've tried a lot of variations of the working delete button that look something like this (and none work):</p> <pre><code>&lt;%= link_to 'Make Public', { :controller =&gt; "posts", :action =&gt; "update", :id =&gt; post, :public =&gt; true, :post =&gt; post }, :method =&gt; :put, :remote =&gt; true %&gt; </code></pre> <p>The only way that seems to work is with a form, but this requires that the user click the <code>Update Post</code> button:</p> <pre><code>&lt;%= form_for(post, :remote =&gt; true) do |f| %&gt; &lt;div class="field"&gt; &lt;%= f.label :public %&gt;&lt;br /&gt; &lt;%= f.check_box :public %&gt; &lt;/div&gt; &lt;div class="actions"&gt; &lt;%= f.submit %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>So, in Rail3 what is the proper way to update a single attribute? (Is there more fitting verbiage?) Can it be done using a link or button? Do I have to use a form? Is there a Rails3 way (like destroy.js.erb) to add an onclick/onchange event or do I need to develop my own JavaScript?</p> <hr> <p>Zabba's answer is great; however, I ultimately used a hidden form submitted via JavaScript (specifically jQuery).</p> <p>In the view:</p> <pre><code>&lt;div&gt; &lt;%= form_for(post, :remote =&gt; true) do |f| %&gt; &lt;%= f.hidden_field :public, { :value =&gt; !post.public } %&gt; &lt;% end %&gt; &lt;% if post.public == true %&gt; &lt;div class="pp"&gt;Public&lt;/div&gt; &lt;% else %&gt; &lt;div class="pp"&gt;Private&lt;/div&gt; &lt;% end %&gt; &lt;/div&gt; </code></pre> <p>The JavaScript:</p> <pre><code>$('.pp').live('click', function(){ $(this).siblings('form').submit(); }); </code></pre> <p>Comments on the two approaches? Is one more idiomatic?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload