User.id未以表单

时间:2015-06-22 21:49:42

标签: ruby-on-rails

我有2个模特,促销和用户。

Promo belongs_to :user
User has_many :promos

在我的路由中,我有嵌套资源:

  devise_for :users
  resources :users do
    resources :promos
  end

我有一个表单来创建新的宣传片,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 %>

问题是,user.id没有保存在数据库中,因此我在执行时得到nil

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正在“正确”传递(为什么提交后是user_id?)

  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"}

1 个答案:

答案 0 :(得分:5)

当您使用嵌套路由时,您需要从参数中获取父ID并将其与表单参数合并。

当您发布表单时,参数看起来像这样:

{
  user_id: 1,
  promo: {
   title: "¡Ay, caramba!"
  }
}

执行params.require(:promo)...对params散列进行切片,以便只获取promo密钥。

def promo_params
  params[:promo].permit(:title,:description,:image)
                .merge(user_id: params[:user_id])
end