Вопрос

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
Это было полезно?

Решение

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.

Другие советы

you can also try:

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

here are the docs for that: http://apidock.com/rails/ActiveRecord/Persistence/becomes

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top