如何通过created_at命令habtm-association的集合

时间:2014-12-11 12:58:54

标签: ruby-on-rails ruby-on-rails-4

我有三个主要的类:用户,词汇和标签。用户有很多标签。标签拥有并且属于许多Vocabs(反之亦然)。 如何通过Vocab-Object获取标签集合?

@vocab.tag

从连接表中获取标签,该表没有created_at列。 有没有方便的方法来解决这个问题?

我对Rails很陌生,请原谅我,如果这很明显的话。

编辑:我刚试过

@tags = @vocab.tags.order('tags.created_at DESC')

但没有成功。

电脑说:

Started GET "/users/1/vocabs/61" for 127.0.0.1 at 2014-12-11 15:41:15 +0100
Processing by VocabsController#show as HTML
Parameters: {"user_id"=>"1", "id"=>"61"}
User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1 LIMIT 1
Vocab Load (0.3ms)  SELECT  "vocabs".* FROM "vocabs"  WHERE "vocabs"."user_id" = ? AND "vocabs"."id"      
                    = ?  ORDER BY created_at DESC LIMIT 1  [["user_id", 1], ["id", 61]]
Tag Load (0.5ms)  SELECT DISTINCT "tags".* FROM "tags" INNER JOIN "tags_vocabs" ON "tags"."id" = 
                  "tags_vocabs"."tag_id" WHERE "tags_vocabs"."vocab_id" = ?  [["vocab_id", 61]]
Rendered shared/_error_messages.html.erb (0.2ms)
Rendered vocabs/show.html.erb within layouts/application (10.7ms)
Rendered layouts/_shim.html.erb (0.1ms)
Rendered layouts/_header.html.erb (1.1ms)
Completed 200 OK in 602ms (Views: 587.3ms | ActiveRecord: 1.2ms)

控制器操作如下所示:

def new_tag
  @user = current_user
  @vocab = @user.vocabs.find(params[:id])
  @tags = @vocab.tags.order('tags.created_at DESC')
  @tag = current_user.tags.build(name: params[:tag])

  if @tag.save
    @vocab.tags<<@tag
    flash.now[:success] ='Tag successfully created.'
    redirect_to user_vocab_path(@user, @vocab)
  else
    flash.now[:danger] = "Tag could not be created!"
    render :action => "show"
  end
end

0 个答案:

没有答案