【问题标题】:Rails nested attributes "no implicit conversion of Symbol into Integer" for has_many association用于has_many关联的Rails嵌套属性“没有将符号隐式转换为整数”
【发布时间】:2018-09-29 15:06:24
【问题描述】:

以下是型号代码。

user.rb

  has_many :teams, dependent: :destroy
  has_many :companies, dependent: :destroy

  after_create :create_tables!

  def create_tables!
    companies.create!
    Team.create!(user_id: self.id, company_id: Company.where(user_id: self.id).first.id)
  end

company.rb

belongs_to :user    

has_many :teams, inverse_of: :company, dependent: :destroy
has_many :users, through: :teams

accepts_nested_attributes_for :teams

team.rb

belongs_to :user
belongs_to :company, inverse_of: :teams

以下是我的控制器代码

companies_controller.rb

def new
    @company = current_user.companies.new
    @company.build_teams
end


def update
    current_user.companies.first.update_attributes(company_params)
    respond_to {|format| format.js}
end

  private

  def company_params
    params.require(:company).permit(:name, :about, :problem, :solution, :logo, :url, :email, :phone, :category, :started_in,
                                    teams_attributes: [:position, :admin])
  end

观看次数

<%= form_with model: @company, method: :put do |f| %>
  <%= f.fields_for :teams_attributes, @company.teams.first do |team| %>
              <%= team.hidden_field :admin, value: true %>
              <%= team.text_field :position, placeholder: 'Eg: CEO', class: 'input' %>
          <% end %>
<%= f.submit 'Next' %>
<% end %>

当我在 Rails 控制台中尝试此操作时,它可以工作并保存在 db 中,在视图中参数也很好。它在下面

但在视图中它说

TypeError in CompaniesController#update no implicit conversion of Symbol into Integer

【问题讨论】:

    标签: ruby-on-rails ruby postgresql associations nested-attributes


    【解决方案1】:

    应该是f.fields_for :teams 而不是f.fields_for :teams_attributes

    <%= form_with model: @company, method: :put do |f| %>
      <%= f.fields_for :teams, @company.teams.first do |team| %>
        <%= team.hidden_field :admin, value: true %>
        <%= team.text_field :position, placeholder: 'Eg: CEO', class: 'input' %>
      <% end %>
      <%= f.submit 'Next' %>
    <% end %>
    

    【讨论】:

    • 嗨@H Dox,我已经更改了属性。现在新的参数是...ibb.co/nKQu4K。现在公司名称和职位都没有保存到数据库中。
    • 参数对我来说似乎是正确的。你能从 Rails 控制台粘贴查询日志吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多