将主题属性与书签相关联

时间:2015-02-20 03:47:04

标签: ruby-on-rails ruby

我试图创建一个新的书签,因此它与主题相关联。每次我尝试这样做,我的topic_id is nil

这是我的bookmark_controller的创建方法:

def create
   @bookmark = Bookmark.new(params[:bookmark].permit!)
   #@topic = Topic.find(params[:topic_id])
   @bookmark.topic_id = @topic_id
   @bookmark.user = current_user
   authorize @bookmark

if @bookmark.save
  flash[:notice] = "Bookmark was saved."
  redirect_to [@topic, @bookmark]
else
  flash[:error] = "There was an error, try it again."
  render :new
end
end

Bookmark.rb

    class Bookmark < ActiveRecord::Base

     belongs_to :topic
     belongs_to :user
     has_many :likes, dependent: :destroy
     end

2 个答案:

答案 0 :(得分:1)

@BartDangus,

您需要在参数中传递主题ID。否则,无法知道书签与哪个主题相关联。在主题下嵌套书签最有意义,以便始终发送主题ID。我在评论中读到你从Topic发表了Bookmark;你能详细说明原因吗?

如果您嵌套书签,则将@bookmark.topic_id = @topic_id更改为@bookmark.topic = Topic.find(params[:topic_id])将有效。

希望这有帮助!

答案 1 :(得分:0)

您的问题是@topic_id变量。未定义时,变量返回nil。

我建议改变这个:

#@topic = Topic.find(params[:topic_id])
@bookmark.topic_id = @topic_id

到此:

@topic = Topic.find(params[:topic_id])
@bookmark.topic = @topic

或者这个:

#@topic = Topic.find(params[:topic_id])
@bookmark.topic_id = params[:topic_id]