Rails Simple_Form关联不起作用

时间:2013-10-27 20:11:22

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

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 %>

1 个答案:

答案 0 :(得分:0)

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

 accepts_nested_attributes_for :tunes

然后向控制器添加强参数,例如

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

注意:我假设你正在使用rails 4