【问题标题】:What's wrong with this Ruby on Rails & jQuery code?这个 Ruby on Rails 和 jQuery 代码有什么问题?
【发布时间】:2011-03-13 07:43:06
【问题描述】:

所以我正在构建一个应用程序,让用户粘贴视频的 url,然后使用嵌入的 jquery API 输出缩略图。然后,当点击缩略图时,嵌入的视频就会出现。

但是,我在控制器中收到此错误:

NoMethodError in VideosController#create

You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.save

这是我的视频控制器:

def new
  @video = Video.new
end

def create
  @video = Video.new(params[:video])

  respond_to do |format|
    if @article.save
      format.html #{ redirect_to(@video, :notice => 'Article was successfully created.') }
    else
      format.html { render :action => "new" }
    end
  end
end

这是我的 application.js 文件:

$(document).ready(function() {

$("li a").embedly({}, function(oembed, dict){
  if ( oembed == null)
    return;
  var output = "<a class='embedly' href='#'><img src='"+oembed.thumbnail_url+"' /></a><span>"+oembed.title+"</span>";
  output += oembed['code'];
    $(dict["node"]).parent().html( output );
});
   $('a.embedly').live("click", function(e){
    e.preventDefault();
    $(this).parents('li').find('.embed').toggle();
  });
});

这是我的new.html.erb 观点:

 <%= form_for(@video) do |f| %>
 <% if @video.errors.any? %>
   <div id="errorExplanation">
     <h2><%= pluralize(@video.errors.count, "error") %> prohibited this video from being saved:</h2>

  <ul>
  <% @video.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
</div>
<% end %>
<div class="field">
  <%= f.label :video_url %><br />
  <%= f.text_field :video_url %>
</div>
<div class="actions">
  <%= f.submit %>
</div>
<% end %>

 <div id="video_div">
<li><a href="<%= @video.video_url %>">Video</a></li>
 </div>

我在这里做错了什么?我需要采取哪些后续步骤才能完成这项工作?

附:我包括了所有必要的文件。

【问题讨论】:

    标签: jquery ruby-on-rails ruby ajax


    【解决方案1】:
    def create
      @video = Video.new(params[:video])
    
      respond_to do |format|
        if @article.save
    

    视频或文章?

    【讨论】:

      【解决方案2】:

      在您尝试保存@article 的视频控制器中。你想保存@video

      【讨论】:

      • 这意味着您没有create.html.erb 视图。在这一点上,我们确实遇到了与您原来的问题不同的问题。
      • 那是因为您可能没有创建操作的视图。在实践中,大多数人会重定向到显示记录的操作(例如显示、索引或您喜欢的任何内容)。
      • 是的,我意识到了这一点,所以我只需在控制器中使用format.html { render :action =&gt; "new" } 重定向回new 视图。但是,现在视频的缩略图没有出现。只有一个链接显示“视频”,可将您带到 youtube 视频。
      • 对;您将希望对 ajax 请求返回与“正常”http 请求不同的响应。您可以返回一个 html 片段或一些 json 以便在客户端使用。
      • 是的,所以我在控制器中执行format.jsformat.json 之类的操作?我应该返回的 html 片段是什么?对不起,菜鸟问题大声笑
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多