User.id is not saved in the form
I have 2 models, promo and users.
Promo belongs_to :user
User has_many :promos
In my routing, I have nested resources:
devise_for :users
resources :users do
resources :promos
end
I have a form to create new promos, simpleform
<%= simple_form_for [current_user, @promo] do |f| %>
<%= f.input :title, label: "Título de la promoción" %>
<%= f.input :image, label: "Imágen de la promoción", class: "" %>
<%= f.input :description, :as => :text, label: "Descripción de la promoción", :input_html => {class: "materialize-textarea"} %>
<%= f.input :title, label: "Pabrasecreta", class: "validate", input_html: {length: "10"} %>
<%= f.submit "Crear Palabra secreta" , class: "right btn" %>
<% end %>
The problem is that user.id is not saved in the database, so I get nil
when I execute:
p = Promo.last
=> #<Promo id: 13, created_at: "2015-06-22 21:44:01", updated_at: "2015-06-22 21:44:01", title: "adad", description: "dasfadf", word_id: nil, shop_id: nil, limit: nil, image: "nevera4.jpg", user_id: nil>
Params are passed "correctly" (why user_id after commit?)
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4ckcpcgiKlJVFU3GmvzA1i7JrseE7Yq5IW84uqUtDH4=", "promo"=>{"title"=>"adad", "image"=>#<ActionDispatch::Http::UploadedFile:0x007ff4dec8b510 @tempfile=#<Tempfile:/var/folders/n1/hsg_rvx906lgk_81lrm1x5xr0000gn/T/RackMultipart20150622-13699-1rmge4a>, @original_filename="nevera4.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"promo[image]\"; filename=\"nevera4.jpg\"\r\nContent-Type: image/jpeg\r\n">, "description"=>"dasfadf"}, "commit"=>"Crear Palabra secreta", "user_id"=>"1"}
+3
Gibson
source
to share
1 answer
When you use nested routes, you need to get the parent id from the parameters and combine it with the form parameters.
When you post the form, the parameters look something like this:
{
user_id: 1,
promo: {
title: "¡Ay, caramba!"
}
}
Execution params.require(:promo)...
slices the params hashes so you only get the key promo
.
def promo_params
params[:promo].permit(:title,:description,:image)
.merge(user_id: params[:user_id])
end
+4
max
source
to share