I have a form that I want to submit along with the user_id of the current user. I am new to strong params. I have tried this but the user_id is not POSTing, nor do I get any errors.
In Rails 3 I would do this:
params[:question][:user_id] = current_user.id
@question= Question.new(params[:question])
I want the current_user.id to be added to the submission under the new Question.user_id
def new_mc
@question = Question.new(user_params)
4.times { @question.answers.build }
end
def user_params
params.
permit(:user_id).
merge(user_id: current_user.id)
end
I wanted to put require(:question). but it is nil. This is the log:
SQL (2.7ms) INSERT INTO "questions" ("active", "category", "content", "created_at", "product_id", "question_type", "updated_at") VALU
ES (?, ?, ?, ?, ?, ?, ?) [["active", false], ["category", "ip_voice"], ["content", "what is going on"], ["created_at", Wed, 23 Apr 2014
14:12:07 UTC +00:00], ["product_id", 1], ["question_type", "MC"], ["updated_at", Wed, 23 Apr 2014 14:12:07 UTC +00:00]]
SQL (0.2ms) INSERT INTO "answers" ("content", "correct", "created_at", "question_id", "updated_at") VALUES (?, ?, ?, ?, ?) [["conten
t", "this "], ["correct", true], ["created_at", Wed, 23 Apr 2014 14:12:07 UTC +00:00], ["question_id", 25], ["updated_at", Wed, 23 Apr 2
014 14:12:07 UTC +00:00]]
So you can see there is not attempt to INSERT the user_id
The controller action is the new_mc above, the Form:
<h1>New Multiple Choice Question</h1>
<%= form_for @question, url: new_mc_question_path(@question) do |f| %>
<%= render 'shared/error_questions' %>
<%= f.label :content, "Question" %><br>
<%= f.text_field :content, class: "input-lg" %>
<%= f.label :category %><br>
<%= f.select :category, [ ["IP Voice Telephony", "ip_voice"], ["IP Video Surveillance", "ip_video_surveillance"], ["IP Video Telephony", "ip_video_telephony"], ["Enterprise Gateways", "enterprise_gateways"], ["Consumer ATAs", "consumer_atas"], ["IP PBX", "ip_pbx"] ], {prompt: "Select Category"}, class: "input-lg" %>
<%= f.label :product_id %><br>
<%= f.collection_select :product_id, Product.all, :id, :name, {prompt: "Select a product"}, {class: "form-control input-lg"} %>
<%= f.label :active %><br>
<%= f.check_box :active %>
<%= f.select :question_type, [["Multiple Choice", "MC"]], {class: "form-control input-lg"}, style: "visibility: hidden" %>
<h1>Answers</h1>
<%= f.fields_for :answers do |builder| %>
<%= render 'four_answers', :f => builder %>
<% end %>
<script>
$(document).ready(function(){
$("#question_active").bootstrapSwitch('onText', 'Active');
$("#question_active").bootstrapSwitch('offText', 'Off');
$("#question_active").bootstrapSwitch('size', 'large');
});
</script>
Exact Solution:
def create
@question = Question.new(question_params)
def question_params
params.require(:question).permit(:content, :question_type, :category, :product_id, :active, :user_id, answers_attributes: [ :content, :correct, :question_id ] ).
merge user_id: current_user.id
end