我有三个模型:User
,Post
和, Reply
。Anuser
有很多posts
和comments
。一个帖子有很多replies
,属于一个user
,一个reply
属于一个post
和一个user
。
路线.rb:
resources :posts do
resources :replies
end
架构.rb:
create_table "posts", :force => true do |t|
t.text "content", :limit => 255
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "title"
end
create_table "replies", :force => true do |t|
t.text "content"
t.integer "post_id"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
这就是我创建评论的方式:
评论控制器.rb:
def create
@post = Post.find(params[:post_id])
@reply = @post.replies.build(params[:reply])
if @reply.save!
flash[:success] = "reply created!"
redirect_to post_path(@post)
else
redirect_to post_path(@post)
end
end
回复/_form.html.erb:
<%= form_for([@post, @post.replies.build]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Enter reply content" %>
</div>
<%= f.submit "Reply", class: "btn btn-large btn-primary" %>
<% end %>
提交表单后,我收到此错误:
Validation failed: User can't be blank
我假设它是因为回复的属性user_id
为空:
回复.rb
validates :user_id, presence: true
我不确定如何填写该属性。我不能把它放进去Reply
attr_accesible
,因为这会损害应用程序的安全性(据我所知)。
有什么建议可以解决这个问题吗?