Вопрос

I am using single tablable inheritance(STI) to create different types of articles. But now I have problem while creating articles.(I can do it only in console).

Here are my models

Article.rb

class Article < ActiveRecord::Base
  attr_accessible :content, :title      
  validates :title, :presence => true
end

And TutorialArticle.rb

class TutorialArticle < Article
  attr_accessible :author  
  validates :author, :presence => true          
end

Here is my _form

<%= form_for(@article) do |f| %>
    <%= f.hidden_field :type %>    

    <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>

  <%= render :partial => "edit" + f.object.type.downcase, :locals=>{:f=>f} %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

But now I have a problem in article_controller.rb in create method

def create
    # create the desired subtype based on the hidden field :type in the form        
    @article = Object.const_get(params[:article][:type]).new(params[:article])      

    if @article.save
      flash[:notice] = "Successfully created post."
      redirect_to @article
    else
      render :action => 'new'
    end
  end

Now when I fill in the form and press Create Article button, I get the folloiwing error

undefined method '[]' for nil:NilClass

I even tried to hard code to understand what is wrong and if I try to change @article = Object.const_get(params[:article][:type]).new(params[:article])

to

 @article = TutorialArticle.new(params[:article]) 

my create method doesn't save the article. it just redirects to create new article page.

Could you please help me to solve the problem?

Это было полезно?

Решение

Ok, the printing of params helped. Add this to your TutorialArticle model:

def self.model_name
  return Article.model_name
end

This will make your forms pass article instead of tutorial_article, and the rest should work as expected. You'll need this override in all your other Article subclasses.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top