User
、Post
および、の3 つのモデルがありReply
ます。Anには とuser
がたくさん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
。アプリのセキュリティが損なわれるからです (私の知る限り)。
これを解決するための提案はありますか?