【问题标题】:Rails Simple_Form Association Not WorkingRails Simple_Form 关联不起作用
【发布时间】:2013-10-27 20:11:22
【问题描述】:

RoR 的新手。我正在制作一个简单的博客来发布音乐条目。我有两个模型 Tune 和 Artist ,其中一个曲调属于一个艺术家。我正在使用 simple_form 来呈现我的表单。我遇到的问题是 simple_form 正在提取正确的关联,但是当我单击提交时,它没有正确保存关联并且验证没有通过。代码如下:

class Tune < ActiveRecord::Base
  belongs_to :artist
  validates :artist, presence: true
end

class Artist < ActiveRecord::Base
  has_many :tunes
end

数据库架构

ActiveRecord::Schema.define(version: 20131027190309) do

  create_table "artists", force: true do |t|
    t.string   "name"
    t.string   "real_name"
    t.string   "gender"
    t.string   "city"
    t.string   "country"
    t.string   "artist_soundcloud_link"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "tunes", force: true do |t|
    t.string   "soundcloud_link"
    t.string   "download_link"
    t.string   "download_label"
    t.string   "name"
    t.string   "style"
    t.boolean  "mix"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "artist_id"
  end

  add_index "tunes", ["artist_id"], name: "index_tunes_on_artist_id"

end

我的表格

<%= simple_form_for @tune, :html => { :class => 'form-horizontal' } do |f| %>
  <%= f.input :name %>
  <%= f.input :soundcloud_link %>
  <%= f.input :download_label %>
  <%= f.input :download_link %>
  <%= f.input :mix %>
  <%= f.association :artist%>
  <%= f.button :submit %>
<% end %>

【问题讨论】:

    标签: ruby-on-rails-4 simple-form


    【解决方案1】:

    将以下内容添加到您的 Tune 模型中

     accepts_nested_attributes_for :tunes
    

    然后将强参数添加到您的控制器,例如

    params.require(:artist).permit( :id, :name, ... , tune_attributes: [:id, :name, :real_name, ...] )
    

    注意:我假设您使用的是 rails 4

    【讨论】:

    • 仍然遇到同样的问题。我认为你是对的,它与嵌套属性有关,但在这种情况下,artist 是父类,而 tune 是子类(具有 artist_id 列)。当我阅读文档时,accepts_nested_attributes_for 通常分配给父类,而不是子类。
    • 你为什么要验证 :artist, presence: true ?。艺术家应该在艺术家模型中得到验证。删除它并尝试。您可以通过控制台输出错误吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多