我想创建包含另一个模型在轨道中的窗体。我已经完成了这与使用accep_nested_attibutes和它工作得很好。问题是我在该表中有一个额外的字段,记录每条评论的用户名,我不确定如何在创建新评论时插入该信息。应用程序控制器使用“current_user”方法提供用户名。Rails 3 - 嵌套窗体和默认值
问候,
凯尔
评论模型
class Comment < ActiveRecord::Base
belongs_to :post
before_save :set_username
private
def set_username
self.created_by = current_user
end
end
应用控制器(这仅仅是一个沙盒应用程序,所以我只是把一个字符串中的方法)
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
def current_user
"FName LName"
end
end
显示视图
<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>
柱控制器
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
你看过吗:http://railscasts.com/episodes/197-nested-model-form-part-2? – apneadiving 2011-04-08 19:34:18
我做了,我无法找到任何可以帮助我的地方。 – Kyle 2011-04-08 20:38:31
你应该提供你的意见表格代码 – apneadiving 2011-04-08 20:42:09