2016-08-29 6 views
0

도움이 필요합니다. articles#createcurrent_user.id (Devise gem을 사용)을 가져와야합니다. 나는 이것을 form_forhidden field이라는 의미로 전달하고자합니다. 내가 쓴 :컨트롤러에서 params를 사용하여 hidden_field 값을 얻으려면 form_for를 어떻게 사용할 수 있습니까? create

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

하지만 내가 필요 : 나는 new.html.erb을이 HTML 코드를 작성했습니다

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

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

및 Active Record는 데이터베이스에 개체를 저장했습니다. params을 검사하고 숨겨진 값을 볼 수 없습니다. 나는 두 가지 질문을하고 싶습니다. 1. hidden_fieldform_for에 어떻게 쓸 수 있습니까? 2. 기사에이 숨겨진 값을 만들려면 어떻게해야합니까? params?

+0

이 시도, <% = f.hidden_field : user_id, current_user.id %> 또는 <% = hidden_field_tag ​​: user_id, current_user.id %> – Navin

+0

고맙습니다. 두 번째 버전은 작업입니다 – Vladimir

답변

1

난 당신이 원하는 것을 생각 해보 것은 :

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

그리고 컨트롤러에서 당신이 USER_ID 매개 변수를 허용하는지 확인 (일반적으로 article_params에서). 숨겨진 필드가 조작 할 수 있기 때문에

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 
+0

더 포괄적 인 답변을 주셔서 감사합니다. 그것은 일이다. – Vladimir

+0

당신은 나의 답변을 클릭하여 대답이었고이 질문을 닫을 수 있습니다. – siegy22

+0

어디에서 클릭 할 수 있습니까? – Vladimir

0

현재 로그인 한 사용자의 경우, current_ 도우미를 사용할 수 있습니다. 사용자 모델이 '사용자'라고 가정합니다.

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