Vladimir
Vladimir

Reputation: 67

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

I need your help.I need get current_user.id (I use Devise gem) to articles#create. I wanna pass it by means form_for and hidden field. I've written:

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

I've got:

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

but I need:

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

I've written this html code in new.html.erb

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

and Active Record saved object to database.I inspect params and I don't see my hidden value. I wanna ask you two question: 1. How can I write hidden_field in form_for? 2. How can I get to articles#create this hidden value by means params?

Upvotes: 0

Views: 435

Answers (2)

siegy22
siegy22

Reputation: 4413

I think what you want is:

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

And then in your controller (usually in article_params) make sure that you permit the user_id parameter.

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

A better way to do this would be setting it server-side, because the hidden field could be manipulated.. as an example:

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

Upvotes: 1

Tony Vincent
Tony Vincent

Reputation: 14362

With devise, for the current signed-in user, current_ helper is available. Assuming your user model is 'user'. Try

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

Upvotes: 0

Related Questions