2016-03-28 25 views
1

我是Rails的新手。我想通過控制器將參數傳遞給數據庫,但是我收到此錯誤參數丟失或值爲空:轉推。我認爲問題在於傳遞參數的方式。錯誤:param丟失或值爲空:轉推

下面是這個視圖

 <% for @p in @posts %> 

    <div class="panel panel-default post-panel"> 
     <div class="panel-body row"> 

     <div class="col-sm-1"> 
      <img src="/avatar.png" class="rounded-img" height="50px" width="50px"> 
     </div> 
     <div class="col-sm-11"> 
      <p class="post-title"><a href="/user/<%= User.find(@p.user_id).username %>" class="post-owner"><%= User.find(@p.user_id).username %></a> <span class="post-creation">- <%= @p.created_at.to_formatted_s(:short) %></span></p> 
      <p class="post-content"><%= @p.content %></p> 
     </div> 
     <div class="col-sm-12"> 
      <p class="post-links"> 
      <span class="glyphicon glyphicon-comment g-links" aria-hidden="true"></span> 


      **<%= form_for Retweet.new do |f| %> 
       <%= hidden_field_tag current_user.id, (:user_id) %> 
       <%= hidden_field_tag @p.id, (:post_id) %> 
       <%= f.submit "Retweet", class:"btn btn-primary"%>** 


      <% end %> 

這裏是控制器

def new 
     @retweet = Retweet.new 
    end 

    def create 
       @retweet = Retweet.new(post_params) 
       redirect_to(:back) 
    end 

    private def post_params 
      params.require(:retweet).permit(:user_id, :post_id) 
    end 
end 
+0

短短几年更多的評論: 在fiew,不命名變量'@ p'。對於那些可以在其他視圖中訪問的人來說,這也是一個非常糟糕的名字。 '後'將是一個更好的。 對'avatar.png'使用'image_tag'輔助方法。當您開始使用CDN時,您會遇到麻煩。 –

回答

0

你應該閱讀了關於在Rails的基本REST控制器一些教程。您的創建操作未保存轉發。

def create 
    @retweet = Retweet.new(post_params) 
    if @retweet.save 
    redirect_to(:back) 
    else 
    render action: 'new' 
    end 
end 

編輯:剛纔注意到你的形式是所有錯誤:

<%= form_for Retweet.new do |f| %> 
    <%= f.hidden_field :user_id, current_user.id %> 
    <%= f.hidden_field :post_id, @p.id %> 
    <%= f.submit "Retweet", class:"btn btn-primary"%>** 
    <% end %> 

你要知道,你不應該讓settign這樣user_ID的,這是很容易改變它,因此更動你的數據。相反,你應該添加這retweet#create

@retweet.user = current_user 
+0

我仍然收到相同的錯誤:參數: { 「UTF8」=> 「✓」, 「authenticity_token」=> 「TDvi8Poxr3QeNsYTw2JWx13NHevm2CSTvVqzrSxA4z3ZuSnyCe/A/vaiKsCHyW9ddolR/dM8TFhi9et/deB2tQ ==」, 「POST_ID」=>「16 「, 」commit「=>」轉推「} – John

+0

啊,當然是。隱藏的字段不在轉推參數中。幹得好。您應該閱讀教程或基本的REST。我更新了我的答案。 –

相關問題