lundi 2 juin 2014

Rails 4 STI saving nested model


Vote count:

0




I'm using paperclip to store images on a model called asset.


Because I want to use these images when I create articles, I need to be able to upload (and create the models) before saving the actual post/article.


articles are a kind of posts, and are the only kinds of posts which can have assets - which is why I used STI in the first place. The problems arise when I try to save a nested asset through a call to @post.save in my PostsController.


This is a brief structure of my model hierarchy



- post.rb
- article.rb
-> has_many asset.rb
- (other kind of post)


In order to upload images while creating an article I've declared assets as a root resource in my routes.rb:



# routes.rb
resources :posts
resources :assets


Though in my asset.rb class I have defined the belongs_to relationship:



#asset.rb
class Asset
belongs_to :article, class_name: 'Post', foreign_key: 'post_id'
end


And this is the table defined in schema.rb:



create_table "assets", force: true do |t|
t.integer "post_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
end


However, the shit hits the fan when I try to save my newly created article in my PostsController:



def create
# type_class yields Article in this particular case.
@post = type_class.new(post_params)
@post.author = current_user
if @post.save
redirect_to post_path(@post)
else
render 'new'
end
end


This yields the following error:



NoMethodError Exception: undefined method `article_id' for #<Asset:0x007fc3c9819568>


Any help would be greatly appreciated.



asked 42 secs ago






Aucun commentaire:

Enregistrer un commentaire