Reputation: 37
I am new to rails and trying to set the "type" of a subclass in my create controller. How do I go about this? Here is my code:
Post.rb
class Post < ActiveRecord::Base
attr_accessible :body, :name, :song_id, :user_id, :artist_id, :type
belongs_to :song
belongs_to :user
belongs_to :artist
end
Picture.rb
class Picture < Post
end
And finally the controller:
def create
@picture = Post.new(params[:picture])
@picture.type = "Picture"
if @picture.save
redirect_to @artist, :notice => "Successfully posted picture."
else
render :action => 'new'
end
end
Upvotes: 1
Views: 1092
Reputation: 1562
you can also try:
@picture = Post.new(params[:picture]).becomes(Picture)
here are the docs for that: http://apidock.com/rails/ActiveRecord/Persistence/becomes
Upvotes: 1
Reputation: 6704
Although I don't see why the code you have wouldn't work, it would be better to do
@picture = Picture.new(params[:picture])
:type
will be automatically set to "Picture"
if you do this.
Upvotes: 2