【问题标题】:How to save selected values from one table column to another table column如何将选定值从一个表列保存到另一表列
【发布时间】:2020-02-15 08:27:57
【问题描述】:

我是 Rails 新手,正在努力学习。在我的简单表单中,我创建了一个下拉选择,其中包含从名为专业的表中生成的数据。这部分工作正常,我可以选择多个值。我正在使用 mysql 数据库。

当我单击提交按钮时,我需要将所选值保存到另一个名为 users 的表中名为 my_professions 的列中。我不知道该怎么做。 我收到此错误

我的表单

<%= simple_form_for @user, url: wizard_path, method: :put do |f| %>
<%= collection_select(:f, :professions_id, Profession.where.not(name: nil), :id, :name, {:multiple => true}, {:class=>'js-example-basic-multiple', :id=>'jsmultipleddd'}) %>
<%= f.submit "Save", :class => 'btn blue'  %> 
<% end %>

我已尝试将此添加到用户模型中

user.rb

class User < ApplicationRecord

has_many :professions
accepts_nested_attributes_for :professions

serialize :my_professions, Array
end

这就是职业模特

professional.rb

class Profession < ApplicationRecord
belongs_to :user
end


我的参数看起来像这样

registration_steps_controller.rb

def user_params

  params.require(:user).permit(:gender,:practitioner_website, :public_health_insurance, clinic_images: [], professions: [])

end

application_controller.rb

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:gender, :practitioner_website, :public_health_insurance, clinic_images: [], professions: []])
  devise_parameter_sanitizer.permit(:account_update, keys: [:gender, :practitioner_website, :public_health_insurance, clinic_images: [], professions: []]) 
end

【问题讨论】:

    标签: mysql ruby-on-rails database simple-form


    【解决方案1】:

    首先摆脱accepts_nested_attributes_for :professions。为此,您不需要嵌套属性。

    然后摆脱serialize :my_professions, ArraySerialize 是一种将复杂数据存储在字符串列中的遗留方法。您不需要或不想要这个(永远),因为关联应该存储在 ActiveRecord 的连接表中 - 而不是数组列。这就是 AR 的工作原理,关系数据库也是这样设计的工作原理。

    相反,您想要的是连接模型。您可以使用以下方式生成:

    rails g model user_profession user:belongs_to profession:belongs_to
    

    运行迁移。然后在用户和职业之间设置the associations

    class User < ApplicationRecord
      # ...
      has_many :user_professions
      has_many :professions, through: :user_professions
    end
    
    class Profession < ApplicationRecord
      # ...
      has_many :user_professions
      has_many :users, through: :user_professions
    end
    

    现在我们可以通过 profession_ids 将用户与职业相关联。

    在普通的 Rails 表单中,您可以使用以下命令创建输入:

    <%= f.collection_select :profession_ids, Profession.all, :id, :name, multiple: true ... %>
    

    在 SimpleForm 中使用 the association 助手:

    <%= f.association :professions, ... %>
    

    然后将正确的参数列入白名单:

    def user_params
      # don't jam this into one super long unreadable line
      params.require(:user)
            .permit(
              :gender, :practitioner_website, :public_health_insurance, 
              clinic_images: [], profession_ids: []
            )
    end
    

    【讨论】:

    • 超级好,非常感谢您的详细解答,非常感谢:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多