我是Rails的新手。我想通过控制器将参数传递给DB,但是我收到此错误参数缺失或值为空:转推。我认为问题是在视图中传递参数的方式。
这是视图
<% 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 :(得分: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