1

我有三个模型:User,Post和, Reply。Anuser有很多postscomments。一个帖子有很多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,因为这会损害应用程序的安全性(据我所知)。

有什么建议可以解决这个问题吗?

4

1 回答 1

1

attr_acessible仅当您从属性哈希更新/创建记录时才会影响事物。您始终可以通过直接调用访问器来设置属性,因此在构建回复后,

@reply.user = current_user

应该做到这一点(假设您使用的是为您定义的 devise 或 authlogic 之类的东西current_user。您也可以@reply.user_id直接分配给。

于 2012-11-11T10:06:15.563 回答