I am trying to create a form containing a different model in rails. I accomplished this with accepts_nested_attibutes and it works fine. The problem is that I have an extra field in this table that records the username for each comment, and I'm not sure how to insert this information when creating a new comment. The username is provided by the application controller using the current_user method.
Yours faithfully,
Kyle
Comment Model
class Comment < ActiveRecord::Base belongs_to :post before_save :set_username private def set_username self.created_by = current_user end end
Application Controller (this is just a sandbox application, so I just put a line in the method)
class ApplicationController < ActionController::Base protect_from_forgery helper_method :current_user def current_user "FName LName" end end
Show view
<p id="notice"><%= notice %></p> <p> <b>Title:</b> <%= @post.title %> </p> <div id="show_comments"><%= render 'comments' %></div> <div id="add_comments"> Add Comment <%= form_for @post, :url => {:action => 'update', :id => @post.id}, :html => { :'data-type' => 'html', :id => 'create_comment_form' } do |f| %> <%= f.fields_for :comments, @new_comment do |comment_fields| %> <%= comment_fields.text_area :content %> <%end%> <div class="validation-error"></div> <%= f.submit %> <% end %> </div>
Mail controller
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 => :show, :id => @post.id}, :notice => 'Post was successfully created.') } format.xml { render :xml => @post, :status => :created, :location => @post } else format.html { render :action => "new" } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } end end end
source share