【问题标题】:strong parameters doesn't allow to create nested attributes with json. ActiveRecord::AssociationTypeMismatch error强参数不允许使用 json 创建嵌套属性。 ActiveRecord::AssociationTypeMismatch 错误
【发布时间】:2014-04-26 11:02:25
【问题描述】:

我有 2 个模型:会议和会谈。会议有_many会谈和

accepts_nested_attributes_for :talks, :allow_destroy => true

我发布的参数看起来像这样:

{"id"=>"2", "name"=>"rails4444", "tags"=>"ruby, rails, backbone, javascript", "date"=>"2014-02-22", "organizer"=>"BackboneMeetupGroup", "description"=>"conference with cool speakers", "talks"=>{"title"=>"fdsf", "video_url"=>"fdsf"}, 

我将谈话设置为应该在数据库中创建的位置。

我的 html 看起来像这样:

<input type="text" name="talks[title]" placeholder="Talk Title" />
<input type="text" name="talks[video_url]" placeholder="url" />

当我用谈话更新我的会议模型时,它给了我一个错误:

ActiveRecord::AssociationTypeMismatch(预期对话(#70154003251480),得到数组(#70154000241560)): app/controllers/conferences_controller.rb:25:in `update'

我的控制器看起来像这样:

 def update
    @single = Conference.find params[:id]
    if @single.update_attributes conference_params
      render "conferences/show"
    else
      respond_with @single
    end
  end



  def conference_params
    params.permit(:name, :tags, :date, :organizer, :description, :place, :talks => [:conference_id, :id, :title, :video_url])
  end

为什么会出现 ActiveRecord::AssociationTypeMismatch 错误,我该如何解决?

【问题讨论】:

    标签: ruby-on-rails ruby json activerecord ruby-on-rails-4


    【解决方案1】:

    作为conference has_many talks,您需要一组谈话作为嵌套属性,而不是单个。

    您的输入字段需要如下名称:

    <input type="text" name="conference[talks_attributes][0][title]" />
    

    accepts_nested_attributes 合作。创建这些输入的正常方法是使用

    <%= fields_for :talks do |ff| %>
      <%= ff.text_field :title %>
    <% end %>
    

    Rails Guide on form helpers

    您需要按照 medBo 的建议在 permit 中使用 talks_attributes

    【讨论】:

      【解决方案2】:

      在您的 conference_params 方法中,只需将 _attributes 添加到 talks 符号就像这样 talks_attributes 这样您的方法就变成了:

      def conference_params
        params.permit(:name, :tags, :date, :organizer, :description, :place, :talks_attributes =>  [:conference_id, :id, :title, :video_url])
      end
      

      【讨论】:

      • 我试过这个,但现在谈话是未经允许的参数。:会议负载(0.2ms)选择“会议”。* FROM“会议”在哪里“会议”。“id”=? LIMIT 1 [["id", "2"]] 不允许的参数:id、created_at、updated_at、color、thumb、talks_num、created_at_formatted、updated_at_formatted、talks、conference
      • 这些颜色、拇指、talk_num 是从哪里来的……我认为这不是相关问题?
      猜你喜欢
      • 1970-01-01
      • 2013-07-22
      • 2015-02-14
      • 1970-01-01
      • 2013-04-01
      • 2017-06-03
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多