我对你们这些了不起的人有更多好奇的问题!
我正在创建一个论坛,当您创建一个主题时,您也在同时创建第一个帖子。
我需要将变量分配给某些字段。
示例::user_id => current_user.id,
我没有正确的参数设置,所以很多字段在存储在数据库中时都是 NULL。
楷模
class Topic < ActiveRecord::Base
belongs_to :forum
has_many :posts, :dependent => :destroy
belongs_to :user
accepts_nested_attributes_for :posts
end
class Post < ActiveRecord::Base
belongs_to :topic
belongs_to :user
end
主题控制器
# GET /topics/new
def new
@topic = Topic.new
@topic.posts.build
end
def create
@topic = Topic.new(topic_params)
if @topic.save
#@topic.responses = Post.new(params[:responses])
flash[:success] = "Topic Posted"
redirect_to "/forums/#{@topic.forum_id}"
else
render :new
end
end
def topic_params
# last_post_at = (:last_post_at => Time.now)
params.require(:topic).permit(
:name,
:description,
[:last_poster_id => current_user.id],
[:last_post_at => Time.now],
[:user_id => current_user.id],
:forum_id,
posts_attributes: [:id, :content, :topic_id, :user_id => current.user.id] )
end
后控制器
# GET /posts/new
def new
@post = Post.new
end
def create
@post = Post.new(
:content => params[:post][:content],
:topic_id => params[:post][:topic_id],
:user_id => current_user.id)
if @post.save
@topic = Topic.find(@post.topic_id)
@topic.update_attributes(
:last_poster_id => current_user.id,
:last_post_at => Time.now)
flash[:notice] = "Successfully created post."
redirect_to "/topics/#{@post.topic_id}"
else
render :action => 'new'
end
end
_form 视图/主题
<%= form_for(@topic) do |f| %>
<% if params[:forum] %>
<input type="hidden"
id="topic_forum_id"
name="topic[forum_id]"
value="<%= params[:forum] %>" />
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<%= f.fields_for :posts do |p| %>
<%= p.label :content %><br />
<%= p.text_area :content %>
<% end %>
<%= f.submit :class => "btn btn-primary" %>
<% end %>