如何在Rails中使用单表继承在控制器中设置“类型”?

时间:2013-05-15 17:28:08

标签: ruby-on-rails single-table-inheritance

我是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

2 个答案:

答案 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