我是rails的新手,并尝试在我的create controller中设置子类的“type”。我该怎么做?这是我的代码:
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
最后是控制器:
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
答案 0 :(得分:2)
虽然我不明白为什么你的代码不起作用,但最好还是
@picture = Picture.new(params[:picture])
:type
将自动设置为"Picture"
。
答案 1 :(得分:1)
您也可以尝试:
@picture = Post.new(params[:picture]).becomes(Picture)
以下是这方面的文档:http://apidock.com/rails/ActiveRecord/Persistence/becomes