我如何使用 form_for 以便在 controller#create 中使用参数获得 hidden_field 值

How can i use form_for so as to get a hidden_field value using params in controller#create

我需要你的 help.I 需要 current_user.id(我使用 Devise gem)到 articles#create。我想通过 form_forhidden field 传递它。我写过:

<%= form_for :article, url: articles_path do |f| %>
  <p>
    <%= f.label :title %><br/>
    <%= f.text_field :title %>
  </p>

  <p>
    <%= f.label :text %><br/>
    <%= f.text_area :text %>
  </p>

  <p>
 # It's here
<%= f.hidden_field :user_id %> 

我有:

<input type="hidden" name="article[user_id]" id="article_user_id"/>

但我需要:

<input type="hidden" name="article[user_id]" id="article_user_id" value="2"/>

我在 new.html.erb

中编写了这个 html 代码
<input type="hidden" name="article[user_id]" id="article_user_id" value="<%= current_user.id%>"/>

和 Active Record 将对象保存到 database.I 检查 params 并且我没有看到我的隐藏值。 我想问你两个问题: 1、如何在form_for中写hidden_field? 2. 如何通过params?

获取文章#create this hidden value

通过设计,对于当前登录的用户,current_ 助手可用。假设您的用户模型是 'user'。尝试

<%= hidden_field_tag 'user_id', current_user.user_id %>

我想你想要的是:

<%= f.hidden_field :user_id, value: current_user.id %>

然后在您的控制器中(通常在 article_params 中)确保您允许 user_id 参数。

def article_params
  params.require(:article).permit(:user_id, :title, ...)
end

更好的方法是将其设置在服务器端,因为可以操纵隐藏字段.. 例如:

def create
  @article = current_user.articles.new(article_params)
  if @article.save
    # ...
  else
    # ...
  end
end