1

我是 Rails 新手,并试图在我的创建控制器中设置子类的“类型”。我该怎么做?这是我的代码:

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 

图片.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
4

2 回答 2

2

尽管我不明白为什么您拥有的代码不起作用,但最好这样做

@picture = Picture.new(params[:picture])

:type"Picture"如果您这样做,将自动设置为。

于 2013-05-15T17:30:42.117 回答
1

你也可以试试:

@picture = Post.new(params[:picture]).becomes(Picture)

这里是文档: http: //apidock.com/rails/ActiveRecord/Persistence/becomes

于 2014-06-25T01:17:25.990 回答