Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3 - Nested Forms and Default Values
    text
    copied!<p><br> I am trying to create form that contains another model in rails. I have accomplished this with using accepts_nested_attibutes and it is working great. The problem is I have an additional field in that table that records the User Name for each comment and I am not sure on how to insert that information when a new comment is being created. The username is being supplied by the Application Controller using the "current_user" method.</p> <p>Regards,<br> Kyle</p> <p><strong>Comment Model</strong></p> <pre><code> class Comment &lt; ActiveRecord::Base belongs_to :post before_save :set_username private def set_username self.created_by = current_user end end </code></pre> <p><strong>Application Controller</strong> (This is just a Sandbox app so I just put a string in the method)</p> <pre><code>class ApplicationController &lt; ActionController::Base protect_from_forgery helper_method :current_user def current_user "FName LName" end end </code></pre> <p><strong>Show View</strong></p> <pre><code>&lt;p id="notice"&gt;&lt;%= notice %&gt;&lt;/p&gt; &lt;p&gt; &lt;b&gt;Title:&lt;/b&gt; &lt;%= @post.title %&gt; &lt;/p&gt; &lt;div id="show_comments"&gt;&lt;%= render 'comments' %&gt;&lt;/div&gt; &lt;div id="add_comments"&gt; Add Comment &lt;%= form_for @post, :url =&gt; {:action =&gt; 'update', :id =&gt; @post.id}, :html =&gt; { :'data-type' =&gt; 'html', :id =&gt; 'create_comment_form' } do |f| %&gt; &lt;%= f.fields_for :comments, @new_comment do |comment_fields| %&gt; &lt;%= comment_fields.text_area :content %&gt; &lt;%end%&gt; &lt;div class="validation-error"&gt;&lt;/div&gt; &lt;%= f.submit %&gt; &lt;% end %&gt; &lt;/div&gt; </code></pre> <p><strong>Post Controller</strong></p> <pre><code> def update @post = Post.find(params[:id]) respond_to do |format| if @post.update_attributes(params[:post]) @comments = @post.comments.all format.html { redirect_to({:action =&gt; :show, :id =&gt; @post.id}, :notice =&gt; 'Post was successfully created.') } format.xml { render :xml =&gt; @post, :status =&gt; :created, :location =&gt; @post } else format.html { render :action =&gt; "new" } format.xml { render :xml =&gt; @post.errors, :status =&gt; :unprocessable_entity } end end end </code></pre>
 

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