Rails 从零学习 Rails 记录 (第二天)

yngzij · August 24, 2017 · Last by yngzij replied at August 25, 2017 · 1319 hits

学习 rails 的第二天,一步一步来嘛!!!

添加第二个关联 Model

  • 生成 Model rails generate model Comment commenter:string body:text article:references 这里 comment 和 Comment 生成 Model 一样的
  • 迁移到数据库 rails db:migrate
  • 在文章路由下添加子路由
  • 生成 Controller

在 View 中添加评论功能,其中关键的就是这一段代码了

 <%= form_for([@work, @work.comments.build]) do |f| %>
  <p>
    <%= f.label :commenter %><br>
    <%= f.text_field :commenter %>
  </p>
  <p>
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

再看看对应的 Controller 方法

def show
  @work=Work.find params[:id]
end
def create
 @work=Work.new work_params
 if @work.save
    redirect_to @work
else 
    render 'new'
  end
end
  1. show 方法在 create 成功保存后在 create 方法中重定向调用,显示创建的@work对象数据。
  2. redirect_to 把自己创建好的 work 对象发送给 show 方法,show 方法通过 id 查找到相应的 work 对象
  3. <%= form_for([@work, @work.comments.build]) do |f| %> 因为 create 的路由是 post /works/:work_id/comments(.:format) 评论需要嵌套在文章中,@work 是在 controller 中查找到的对象,在@work model 中用 has_many 关联了,所以能在@work.comments.build 可以用
  4. 如果保存不成功 ,在 new 界面显示错误

** 这里 render ,link_to, redirect_to ** 三者的区别

  • link_to 在网站上生成 超链接 的代码 用于 view 中连接到其他路由
  • render 将指定视图作为响应,这里在没有保存成功 ,render 到'new' 在 new.html.erb 中会将@work错误中的错误显示出来,因为在同一个方法中,显示的就是本方法中的@wrok,而且 render 还能导入代码。
  • redirect_to 重定向,将浏览器重定向到指定的目标,为什么 @work 就是 show 页 @work 不是在 create 方法中创建的一个对象吗?难道因为路由是 work GET /works/:id(.:format) works/show 吗 这里自己的理解也不好,百度了好多也是模模糊糊的 😭

显示评论

代码位置 app/views/articles/show.html.erb

<h2>Comments</h2>
<% @work.comments.each do |comment| %>
  <p>
    <strong>Commenter:</strong>
    <%= comment.commenter %>
  </p>

  <p>
    <strong>Comment:</strong>
    <%= comment.body %>
  </p>
<% end %>

将 Controller 中找到的@work中的 comments 模型内容显示出来,demo 在 (https://github.com/yngzij/rails-) 希望对后来的朋友有帮助

  • 安装和生成框架就算完了 其他重构,验证什么的都很容易理解,redirect_to 和 render 谢谢朋友能解释下 😅 a
  • create 后 redirect_to @work 定向到 show 页面,显示的是 new 中创建的数据,那 show 是怎么获取到的呀 😄

不要拿论坛当日记本,写到自己的博客去。

如果你一天一贴,论坛就全是你的帖子了,写博客是个不错的方法,等你有一定收获了再跟大家分享一下😄

Reply to Rei

好的嘞

Reply to superkun

是哦 好的嘞☺

yngzij closed this topic. 25 Aug 00:58
yngzij reopened this topic. 25 Aug 00:59
You need to Sign in before reply, if you don't have an account, please Sign up first.