Почему simpleform не принимает мою ассоциацию?

Почему simpleform не принимает мою ассоциацию?

Я относительно новичок в рельсах, так что простите меня, если это новичок. Из-за этого я потенциально включаю слишком много информации, просто чтобы убедиться, что я не делаю глупостей.

Я пытаюсь построить простую форму, в которой судья может выбирать различные фокусы, которые они хотят оценивать.

Я получаю следующее сообщение об ошибке:

NameError in Devise/registrations#new

Showing             /Users/wattsb/ruby/rails_projects/social_pitch/app/views/devise/registrations/new.html.erb where line #9 raised:

uninitialized constant Judge::Focu
Extracted source (around line #9):

6:   <%= f.input :email %>
7:   <%= f.input :password %>
8:   <%= f.input :password_confirmation %>
9:   <%= f.association :focus, as: :check_boxes %>
10:   <div class="form-actions">
11:     <%= f.submit "Sign up", class: "btn btn-primary" %>
12:   </div>

Ошибка ссылается на следующее представление

<h2>Sign up</h2>

<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), html: { class: 'form-horizontal'}) do |f| %>
  <%= f.error_notification %>

  <%= f.input :email %>
  <%= f.input :password %>
  <%= f.input :password_confirmation %>
  <%= f.association :focus, as: :check_boxes %>
  <div class="form-actions">
    <%= f.submit "Sign up", class: "btn btn-primary" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>

Форма ссылается на следующие модели:

class Judge < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
  has_many :focus   
  attr_accessible :email, :password, :password_confirmation, :remember_me, :name
end

class Focus < ActiveRecord::Base
  attr_accessible :title
  belongs_to :judge
end

Для этих моделей я выполнил следующие миграции:

class DeviseCreateJudges < ActiveRecord::Migration
  def change
    create_table(:judges) do |t|
      t.string :email,              :null => false, :default => ""
      t.string :encrypted_password, :null => false, :default => ""

      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      t.datetime :remember_created_at

      t.integer  :sign_in_count, :default => 0
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip
      t.timestamps
    end

    add_index :judges, :email,                :unique => true
    add_index :judges, :reset_password_token, :unique => true
  end
end


class AddNameToJudges < ActiveRecord::Migration
  def change
    add_column :judges, :name, :string
  end
end

class CreateFocus < ActiveRecord::Migration
  def change
    create_table :focus do |t|
      t.string :title

      t.timestamps
    end
  end
end


class AddAssociationsBetweenJudgesAndFocuses < ActiveRecord::Migration
  def up
    change_table :focus do |t|
        t.belongs_to :judge 
    end
  end
end

person justalisteningman    schedule 30.06.2013    source источник
comment
Попробуй это. has_many :focus, :class_name => "Focus", :foreign_key => 'judge_id'.   -  person usha    schedule 01.07.2013


Ответы (1)


Попробуй это. has_many :focus, :class_name => "Focus", :foreign_key => 'judge_id'. Это потому, что форма множественного числа фокус - «фокусы». Rails автоматически определяет имя класса и внешний ключ только тогда, когда вы задаете правильную форму множественного числа.

person usha    schedule 01.07.2013
comment
Это сработало! Есть ли в рельсах соглашение, чтобы имена классов не имели неудобных форм множественного числа? - person justalisteningman; 02.07.2013
comment
Что вы имеете в виду, избегайте? Вы должны явно указать имя класса и внешний ключ, если вам не нравится расширенная форма имени вашего класса. - person usha; 02.07.2013
comment
Вы можете использовать инфлектор, чтобы исправить это. Читать - ›api.rubyonrails.org/classes/ActiveSupport/Inflector.html - person usha; 02.07.2013