【问题标题】:How do I get my link to hit the correct controller action?如何让我的链接点击正确的控制器操作?
【发布时间】:2011-04-01 23:18:35
【问题描述】:

我有一个 has_many,通过视频和主题之间的关联,将主题作为独立资源。我想要一个链接,删除该特定主题记录,即关联,而不是视频或主题。

我的主题控制器中有这个方法:

def destroy
  @topicable = Topicable.find(params[:id])
  @topicable.destroy
  respond_to do |format|
    format.html {redirect_to @video}
    format.js
  end
end

我想在我的视频显示视图中使用此链接调用上述方法:

<%= link_to "x", @topicable, :method => :delete, :class => 'topic_delete' %>

但是,这并没有达到我想要的效果。相反,它似乎触发了视频控制器删除操作并删除了视频和关联,而不仅仅是我想要的关联。这些是日志:

Started POST "/videos/468" for 127.0.0.1 at Fri Apr 01 19:15:07 -0700 2011
  Processing by VideosController#destroy as HTML
  Parameters: {"authenticity_token"=>"F2uF4FDDSPw+jHHGtsosGLjHwkDUg/nre5u+WEPPDUY=", "id"=>"468"}
  User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 57 LIMIT 1
  Video Load (0.3ms)  SELECT "videos".* FROM "videos" WHERE "videos"."id" = 468 AND ("videos".user_id = 57) ORDER BY videos.rank_sum DESC LIMIT 1
  Genre Load (0.3ms)  SELECT * FROM "genres" INNER JOIN "genres_videos" ON "genres".id = "genres_videos".genre_id WHERE ("genres_videos".video_id = 468 )
  Topicable Load (0.3ms)  SELECT "topicables".* FROM "topicables" WHERE ("topicables".video_id = 468)
  AREL (0.4ms)  DELETE FROM "topicables" WHERE "topicables"."id" = 93
  AREL (0.1ms)  DELETE FROM "topicables" WHERE "topicables"."id" = 94
  AREL (0.1ms)  DELETE FROM "videos" WHERE "videos"."id" = 468
Redirected to http://localhost:3000/videos
Completed 302 Found in 181ms

我该如何解决这个问题?

这是视频模型:

validates :video_url, :presence => true
validates :title, :presence => true

belongs_to :user 
has_many :video_votes
has_many :voted_users, :through => :video_votes, :source => :user
has_and_belongs_to_many :genres
has_many :topicables, :dependent => :destroy
has_many :topics, :through => :topicables

attr_accessor :topic_names
after_save :assign_topics
before_update :update_rank_sum
default_scope order('videos.rank_sum DESC')

def assign_topics
  if @topic_names
    self.topics << @topic_names.map do |name|
      Topic.find_or_create_by_name(name)
    end
  end
end

话题模型:

belongs_to :video
belongs_to :topic

【问题讨论】:

  • 你也可以发布话题模型吗?
  • 这个问题真的那么难吗???

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


【解决方案1】:

如果@topicable 属于Video 对象,那么它将转到VideosController。您需要手动设置路径:

<%= link_to "x", topicable_path(@topicable), ... %>

【讨论】:

  • ActiveRecord::RecordNotFound in TopicablesController#destroy Couldn't find Topicable with ID=474 这是视频的id,不是我要删除的主题的id...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 2011-01-03
相关资源
最近更新 更多