美文网首页
rails第二课加分题

rails第二课加分题

作者: 青衣小妖 | 来源:发表于2017-03-31 19:45 被阅读36次

    1、在suggestotron里面加一个“扣分”按钮,做的事跟加分按钮相反。

    首先想起来前面rails第二课3-8步骤3里有过这样一个语句是my_topic.votes.first.destroy,参照之前增加票数可以用create,那么减少票数就可以用destroy。于是参照3-9节增加票数的写法

    def upvote

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

    @topic.votes.create

    redirect_to(topics_path)

    end

    得到

    def minusvote

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

    @topic.votes.first.destroy

    redirect_to(topics_path)

    end

    添加到app/controllers/topics_controller.rb里面upvote的下面,然后按照课程里面添加增加票数的按钮方法在app/views/topics/index.html.erb里的

    <%= button_to '+1', upvote_topic_path(topic), method: :post %>

    下面添加一行

    <%= button_to '-1', minusvote_topic_path(topic), method: :post %>

    同理在route.rb里面添加post 'minusvote'到post 'upvote'的下面。

    如此便做好了添加“扣分”按钮的操作。

    2、根据投票分数排序 topics

    在中级课程里我们用 @posts = @group.posts.order("created_at DESC")给文章按照时间排序,这里给投票数排序我们使用sort_by来完成同样的事。

    在app/controllers/topics_controller.rb里index里将@topics = Topic.all变成

    @topics = Topic.all.sort_by{|topic| -topic.votes.count}

    其中意思是将topic按照topic.votes.count(投票数)从小到大来排序,加一个减号-,表示按照相反顺序。

    3、新增一个 'about' 页面

    在终端机运行touch app/views/topics/about.html.erb。

    参照app/views/topics/show.html.erb的内容给about.html.erb添加内容

    About

    Welcome!

    <%= link_to 'Back', topics_path %>

    其中,<%= link_to 'Back', topics_path %>可以让使用这返回到topic列表。

    然后在app/views/topics/index.html.erb最后添加<%= link_to 'About', about_path %>,意思是链接到about页面。

    最后在修改routes.rb,将页面上的About指向‘about’。在routes.rb里面最后一个end上面添加

    get '/about/', to:'topics#about'

    指令详情可以参考http://guides.rubyonrails.org/routing.html

    如此就完成了'about' 页面的添加。

    Ps.当不同页面的表单产生联系时一定要通过修改routes.rb来实现。

    我犯错误的地方就是没有想到要修改routes.rb来让新增的页面与topic产生联系,还有redirect_to(topics_path)语句很重要,这样可以让结果返回,否则你的操作出来结果却不会显示到页面上。

    相关文章

      网友评论

          本文标题:rails第二课加分题

          本文链接:https://www.haomeiwen.com/subject/higvottx.html