Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: Forcing specific values with "strong parameters"

I'm struggling with a form for creating "Projects". Eventually I want to allow only the current user_id but I haven't built the User model or authentication yet so as a placeholder, I'm just hard-coding 1.

app/views/projects/new.html.erb:

<%= form_for(:project, :url => {:action=>'create'}) do |f| %>
<%= f.text_field(:name) %>
<%= f.text_field(:instructions) %>
<%= f.hidden_field( :user_id, {:value=>1}) %>
<%= f.submit('Create Project') %>
<% end %>

app/controllers/projects_controller.rb

  def create
    #save object
    if Project.create( project_params )
        redirect_to(:action=>'show')
    else
        render('new')
    end
  end

  private
    def project_params
      params.require(:project).permit({:user_id => [1]}, :instructions, :max_duration, :active, :max_videos, :hashed_id)
    end

Here's the error I get when I try to submit the form:

Mysql2::Error: Field 'user_id' doesn't have a default value: INSERT INTO `projects` (`created_at`, `instructions`, `updated_at`) VALUES ('2013-08-16 17:38:56', 'sdfgsdf', '2013-08-16 17:38:56')

It appears that the project_params() method is stripping out the user_id. What am I doing wrong?

like image 847
emersonthis Avatar asked Aug 16 '13 17:08

emersonthis


1 Answers

probably is because params[:user_id] is a string, doing something like this should work.

params.require(:project).permit({:user_id => ["1"]}, :instructions, :max_duration, :active, :max_videos, :hashed_id)
like image 141
Orlando Avatar answered Nov 08 '22 18:11

Orlando