Нет ошибки метода в Rails - PullRequest
0 голосов
/ 02 мая 2011
NoMethodError in Pages#new

Showing /Users/janicelloyd/Sites/assignment/app/views/pages/_form.html.erb where line #27 raised:

undefined method `author_id' for #<Page:0x10532f018>
Extracted source (around line #27):

    24:     <%= f.text_area :content %>
    25:   </div>
    26: <div class ="field">
    27: <%= f.collection_select (:author_id, Author.all, :id, :name, :prompt => 'Select') %>
    28: </div>
    29:   <div class="actions">
    30:     <%= f.submit %>

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

Я добавил следующее

Я выполнил рельсы для генерации миграции, она все еще не работает, мои контроллеры выглядят так: Pages controller

class PagesController < ApplicationController
  def index
    @pages = Page.find(:all, :order => 'created_at DESC')
  end

  def show
    @page = Page.find(params[:id])
  end

  def new
    @page = Page.new
  end

  def edit
    @page = Page.find(params[:id])
  end

  def create
    @page = Page.new(params[:page])

    if @page.save
      redirect_to(@page, :notice => 'Page was successfully created.')
    else
      render :action => "new"
    end
  end

  def update
    @page = Page.find(params[:id])

    if @page.update_attributes(params[:page])
      redirect_to(@page, :notice => 'Page was successfully updated.')
    else
      render :action => "edit"
    end
  end

  def destroy
    @page = Page.find(params[:id])
    @page.destroy
  end

  def author
    @pages = @author.pages
  end
end

и контроллер моих авторов

class AuthorsController < ApplicationController
  # GET /authors
  # GET /authors.xml
  def index
    @authors = Author.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @authors }
    end
  end

  # GET /authors/1
  # GET /authors/1.xml
  def show
    @author = Author.find(params[:id])
    @pages = @author.pages

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @author }
    end
  end

  # GET /authors/new
  # GET /authors/new.xml
  def new
    @author = Author.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @author }
    end
  end

  # GET /authors/1/edit
  def edit
    @author = Author.find(params[:id])
  end

  # POST /authors
  # POST /authors.xml
  def create
    @author = Author.new(params[:author])

    respond_to do |format|
      if @author.save
        format.html { redirect_to(@author, :notice => 'Author was successfully created.') }
        format.xml  { render :xml => @author, :status => :created, :location => @author }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @author.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /authors/1
  # PUT /authors/1.xml
  def update
    @author = Author.find(params[:id])

    respond_to do |format|
      if @author.update_attributes(params[:author])
        format.html { redirect_to(@author, :notice => 'Author was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @author.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /authors/1
  # DELETE /authors/1.xml
  def destroy
    @author = Author.find(params[:id])
    @author.destroy

    respond_to do |format|
      format.html { redirect_to(authors_url) }
      format.xml  { head :ok }
    end
  end

  def author_id
    @author = @pages.author
  end
end

author.rb

class Author < ActiveRecord::Base
  has_many :pages
end

page.rb

class Page < ActiveRecord::Base
  belongs_to :author
end

миграции

class CreatePages < ActiveRecord::Migration
  def self.up
    create_table :pages do |t|
      t.string :title
      t.string :excerpt
      t.string :content

      t.timestamps
    end
  end

  def self.down
    drop_table :pages
  end
end


class CreateAuthors < ActiveRecord::Migration
  def self.up
    create_table :authors do |t|
      t.integer :author_id
      t.string :name
      t.string :email

      t.timestamps
    end
  end

  def self.down
    drop_table :authors
  end
end

class AddAuthorIdToAuthors < ActiveRecord::Migration
  def self.up
    change_table :authors do |t|
      t.references :author_id
   end
  end

  def self.down
    remove_column :authors, :author_id
  end
  end
end

class AddAuthorToPages < ActiveRecord::Migration
  def self.up
    change_table :pages do |t|
      t.references :author_id
    end
  end

  def self.down
    remove_column :pages, :author_id
  end
  end
end

Ответы [ 2 ]

2 голосов
/ 02 мая 2011

Это будет означать, что объект, для которого вы строите форму, не имеет атрибута с именем author_id: это правильно?

[править: после просмотра миграции]

Привет Дженис, ты должен написать миграцию следующим образом:

self.up do
  change_table :pages do |t|
    t.references :author
  end
end

Это должно не быть добавлено в таблицу authors вообще.

0 голосов
/ 02 мая 2011

Взгляните на документальный фильм здесь:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select

Я думаю, что вы не установили переменную экземпляра: post (или любую другую)Это, вероятно, должно быть:

<%= f.collection_select (:post, :author_id, Author.all, :id, :name, :prompt => 'Select') %> 28: 29: 30: <%= f.submit %>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...