Creating an object using polymorphic associative rails

I need (or I think) to implement polymorphic association in my model, but something is wrong with me. Let's look at my situation, this is a simple system of questions / answers, and the logic is as follows: - a question can be asked by N answers. - The answer can only be a “textual” XOR (one or another, and not both) “picture”.

Migrations:

class CreateAnswers < ActiveRecord::Migration def change create_table :answers do |t| t.integer :question_id t.references :answerable, :polymorphic => true t.timestamps end end end class CreateAnswerTexts < ActiveRecord::Migration def change create_table :answer_texts do |t| t.text :content t.timestamps end end end class CreateAnswerPictures < ActiveRecord::Migration def change create_table :answer_pictures do |t| t.string :content t.timestamps end end end 

Models * Answer.rb *

 class Answer < ActiveRecord::Base belongs_to :user_id belongs_to :question_id belongs_to :answerable, :polymorphic => true attr_accessible :answerable_type end 

answer_text.rb

 class AnswerText < ActiveRecord::Base TYPE = "text" has_one :answer, :as => :answerable attr_accessible :content end 

answer_picture.rb

 class AnswerPicture < ActiveRecord::Base TYPE = "picture" has_one :answer, :as => :answerable attr_accessible :content end 

controller answers_controller.rb:

 ... def create post = params[:answer] create_answerable(post[:answerable_type], post[:answerable]) @answer = @answerable.answer.new() end private def create_answerable(type, content) @answerable = ('Answer' + type.capitalize).classify.constantize.new(:content => content) @answerable.save end ... 

And see the form (Only these fields):

 ... <div class="field"> <%= f.label :answerable_type %><br /> <%= select("answer", "answerable_type", Answer::Types, {:include_blank => true}) %> </div> <div class="field"> <%= f.label :answerable %><br /> <%= f.text_field :answerable %> </div> ... 

So the problem is when I submit the form, I get this error:

undefined method new' for nil:NilClass app/controllers/answers_controller.rb:52:in create'

Answers? :)

+8
ruby ruby-on-rails polymorphic-associations
source share
1 answer

in relation to has_one , you should use:

 @answerable.build_answer 

or

 @answerable.create_answer 

instead

 @answerable.answer.new 

See the link for more information.

+18
source share

All Articles