填写回复模型的user_id属性(不是attr_accesible的属性)

时间:2012-11-11 09:46:34

标签: ruby-on-rails

我有三个模型:UserPostReplyuser有许多postscomments。帖子有很多replies,属于userreply属于postuser

routes.rb中:

resources :posts do
  resources :replies
end

schema.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

这就是我创建评论的方式:

comments_controller.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为空:

reply.rb

validates :user_id, presence: true

我不确定如何填写该属性。我无法将其放入Reply attr_accesible,因为这会影响应用的安全性(据我所知)。

有任何解决此问题的建议吗?

1 个答案:

答案 0 :(得分:1)

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

@reply.user = current_user

应该做的伎俩(假设您正在使用为您定义current_user的设计或authlogic之类的东西。您也可以直接分配给@reply.user_id