0

new.html.erbRuby on Rails、devise:どのように私はユーザーのテーブルのIDをposts.user_idの列に追加できますか?

<h3>Add post</h3> 

<%= form_tag :controller=>'posts', :action=>'create' do %> 
    <%= label :q, :Title %> 
    <%= text_field :data, :title, :class => :addtextsize %><br/> 
    <%= label :q, :Content %> 
    <%= text_area :data, :content, :rows=>10 , :class => :addtextarea %><br/> 
    <%= label :q, :Category %> 
    <%= select :data, :category_id, @categories_select %><br/> 
    <%= label :q, :Tags %> 
    <%= text_field :data, :tags, :class => :addtextsize %><br/> 
    <%= label :q, :Submit %> 
    <%= submit_tag "Add Post" %> 
<% end %> 

はPostController.rb

私はポストのテーブルに挿入する必要がusers.idを取得
def create 
    @categories_select = Category.all.collect {|c| [ c.category_name, c.id ] } 
    @addpost = Post.new params[:data] 
    if @addpost.save 
     flash[:notice] = "Post has been saved successfully." 
     redirect_to posts_path 
    else 
     flash[:notice] = "Post can not be saved, please enter information." 
     render :new 
     #redirect_to new_post_path 
    end 
end 

のアクションを作成します。どうすればいいですか?

ポストテーブル

        Table "public.posts" 
    Column |   Type   |      Modifiers      
-------------+------------------------+---------------------------------------------------- 
id   | integer    | not null default nextval('posts_id_seq'::regclass) 
title  | character varying(100) | not null 
content  | character varying(500) | not null 
created_at | date     | 
updated_at | date     | 
tags  | character varying(55) | not null default '50'::character varying 
category_id | integer    | not null default 1 
user_id  | integer    | 
Indexes: 
    "posts_pkey" PRIMARY KEY, btree (id) 
+0

はあなたがuser.idに投稿して隠しフィールドを追加することで試してみましたか? – microspino

+0

隠しフィールドを追加するのがいいですか?隠されたフィールドをvulnurableを使用していないのですか? – shibly

+0

Railsはあなたが必要とするすべてのセキュリティを提供していますが、ユーザーIDを隠しフィールドに挿入する危険性はありませんが(ユーザー名ではなく、何か感知できる権利ですか?)、ビューでは@ Banster74に従うこともできます。 – microspino

答えて

3

工夫を使用すると、認証されたユーザーを取得するために使用できるcurrent_userと呼ばれるヘルパーメソッドを提供します。だから、あなたはこのように、フォームで隠しテキスト入力を入れることができます:

<%= hidden_field_tag :user_id, current_user.id %> 

これを、それはparamsのあなたのコレクションに渡すことができます。

他のオプションは、手動でcreate方法でそれを追加することです:

def create 
    @categories_select = Category.all.collect {|c| [ c.category_name, c.id ] } 
    @addpost = Post.new params[:data] 
    @addpost.user_id = current_user.id 
    if @addpost.save 
     flash[:notice] = "Post has been saved successfully." 
     redirect_to posts_path 
    else 
     flash[:notice] = "Post can not be saved, please enter information." 
     render :new 
     #redirect_to new_post_path 
    end 
end 
+0

隠しフィールドを追加するのは良い考えですか?隠されたフィールドをvulnurableを使用していないのですか? – shibly

+0

はい、非表示フィールドには脆弱性が存在します。たとえば、FireBug(または類似のもの)を使用して、隠しフィールドの値を変更することができます。上記の例では、秘密フィールドは認証などに使用されていないため、リスクは低いです。第2の選択肢はより安全です。 – Benster74

関連する問題