1

UserPostおよび、の3 つのモデルがありReplyます。Anには とuserがたくさんpostsありcommentsます。投稿は多数repliesあり、 に属し、userは および に属しreplyます。postuser

ルート.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 に答える