从类中创建动作创建模型

时间:2012-10-28 22:50:32

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord

作为铁杆的新手,我找不到如何解决我的问题^^
我想从一个包含视频网址(如youtube)的文本字段的表单中创建一个VideoPost 由于宝石https://github.com/thibaudgg/video_info,我正在获取视频信息 我想使用我的模型(VideoInformation)保存信息。 但我不知道创作过程应该如何运作 谢谢你的帮助!

我正在尝试在VideoPostsController中创建一个VideoPost,如下所示:

def create
  video_info = VideoInfo.new(params[:video_url])
  video_information = VideoInformation.create(video_info)      #undefined method `stringify_keys' for #<Youtube:0x00000006a24120>
  if video_information.save
    @video_post = current_user.video_posts.build(video_information) 
  end
end

我的VideoPost模型:

# Table name: video_posts
#
#  id                   :integer          not null, primary key
#  user_id              :integer
#  video_information_id :integer
#  created_at           :datetime         not null
#  updated_at           :datetime         not null

我的VideoInformation模型(其名称与VideoInfo gem相同):

# Table name: video_informations
#
#  id              :integer          not null, primary key
#  title           :string(255)
#  description     :text
#  keywords        :text
#  duration        :integer
#  video_url       :string(255)
#  thumbnail_small :string(255)
#  thumbnail_large :string(255)
#  created_at      :datetime         not null
#  updated_at      :datetime         not null

2 个答案:

答案 0 :(得分:3)

  

不知道创建过程应该如何运作

create方法需要带参数的哈希,而不是某些任意对象。您应该使用VideoInfo的方法并将其转换为ActiveRecord可以使用的哈希值。

答案 1 :(得分:2)

我会在VideoInformation模型中添加一个方法,这样你就可以通过传入video_info来创建一个方法:

# app/models/video_information.rb
def self.create_from_video_info(video_info, url)
  video_information = self.new
  video_information.title = video_info.title
  video_information.description = video_info.description
  video_information.keywords = video_info.keywords
  video_information.duration = video_info.duration
  # video_url appears to not be available on video_info,
  # maybe you meant embed_url?
  video_information.video_url = url
  video_information.thumbnail_small = video_info.thumbnail_small
  video_information.thumbnail_large = video_info.thumbnail_large
  video_information.save
  video_information
end

# app/controllers/video_posts_controller.rb
def create
  video_info = VideoInfo.new(params[:video_url])
  video_information = VideoInformation.create_from_video_info(video_info, params[:video_url])

  if video_information.valid?
    current_user.video_posts << video_information
  end
end

此外,您可能希望以不同的方式进行此操作。拥有VideoInformationVideoInfoVideoPost类似乎是多余的。

也许VideoPost模型可以只存储视频的网址,您可以在渲染/使用VideoInfo实例时随时提取VideoPost内容。