繁体   English   中英

我如何使用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

我需要您的帮助。我需要获得current_user.id (我使用Devise gem)来article 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将对象保存到数据库。我检查了params ,但看不到隐藏的值。 我想问两个问题:1.如何在form_for编写hidden_field 2.我该如何通过params #articles创建此隐藏值?

我认为您想要的是:

<%= 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

通过devise,对于当前登录的用户,可以使用current_ helper。 假设您的用户模型是“用户”。 尝试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM