1

背景故事:我正在构建一个站点,该站点将 Soundcloud URL 作为帖子的一部分。目前,我存储他们提供的链接,当用户加载他们的提要视图时,我通过我的 post_helper 检索相关的图像/标题/收藏计数等。我很快意识到这是不可扩展的,并且会影响加载时间。

所以,我认为我应该做的(随时告诉我有更好的方法)是在表单提交时检索 SC/YT 元数据并将其与其他帖子数据(id、用户、内容等)一起存储。 ) 在帖子的表格条目中。我将如何调用辅助方法来检索表单提交并将元数据包含在提交的参数中?

post_helper.rb 摘录:

def soundcloud_info(soundcloud_url, type)  
    begin
        resolve = scClient.get('/resolve', :url => soundcloud_url)
        track_info = scClient.get("/tracks/#{resolve.id}")
    rescue Soundcloud::ResponseError => e
        %Q{ Error: #{e.message}, Status Code: #{e.response.code} }
    end                 
    if type == "title"
        %Q{#{track_info['title']}}
    elsif type == "image"
        %Q{#{track_info['artwork_url']}}
    elsif type == "favCount"
        %Q{Favorite count: #{track_info['favoritings_count']}}              
    end
end

post_controler.rb 摘录:

  def create
    @post = current_user.posts.build(params[:post])
    if @post.save
      flash[:success] = "Your post was successful!"
      redirect_to root_url
    else
      @feed_items = current_user.feed.paginate(page: params[:page])
      render 'static_pages/home'
    end
  end
4

1 回答 1

0

所以显然这很简单......我需要做的就是在调用@post = current_user.posts.build(params[:post]) 之前修改控制器中的参数。我的问题是我试图在助手中这样做。

我还没有完全适应整个事情来获取我所有的必填字段,但这里有一个例子,如果有人提交 SoundCloud 的嵌入 iframe,我如何调整 create 方法来提取 api URL。

micropost_controller.rb 摘录:

def create
  @url = params[:post][:link_html]

  if @url[/^.*src="(https|http):\/\/w.soundcloud.com\/player\/\?url=(.*)">/] 
    params[:post][:link_html] = CGI::unescape($2)
  end

  @post = current_user.posts.build(params[:post])
  if @post.save
    flash[:success] = "Your post was successful!"
    redirect_to root_url
  else
    @feed_items = current_user.feed.paginate(page: params[:page])
    render 'static_pages/home'
  end
end
于 2013-08-28T21:19:10.743 回答