【问题标题】:What is my build method within my form_for helper accomplishing?我的 form_for 助手中的构建方法是什么?
【发布时间】:2017-03-20 02:10:11
【问题描述】:

我刚刚开始学习 Rails,目前正在开发一个淡化的 Facebook 克隆。我想知道我在 form_for 助手中包含的构建方法到底在做什么。这取自The Ruby On Rails Tutorial by Michael Hartl,我们在其中做了类似的事情,但使用的是 Twitter 关注者而不是好友请求。那时我无法理解它,现在我仍然遇到问题。

这是我在用户向其他用户发送好友请求时使用的表单。这是从 @users 部分呈现的表单(因此是 user.id)

<%= form_for(current_user.active_relationships.build) do |f| %>
  <div><%= hidden_field_tag :friend_id, user.id %></div>
  <%= f.submit "Send Friend Request" %>
<% end %>

这将传递给我的 Friendships 控制器...

def create
  @user = User.find(params[:friend_id])
  current_user.send_friend_request(@user)
  redirect_to current_user
end

调用send_friend_reqeust...

def send_friend_request(other_user)
  friend_requests << other_user
end

我的用户模型has_many :friend_requests, through: :active_relationships

它工作正常,但我开始质疑我的 form_for 助手中的 current_user.active_relationships.build 甚至在做什么。在我(非常)未经训练的眼睛看来,该表单似乎传递了一个隐藏值 friend_id,然后 Friendships 控制器使用该值来查找与该 ID 关联的用户数据库记录。

如果我的表单所做的只是提交一个隐藏的用户 ID,那么构建方法的意义何在?我知道它必须做某事,因为删除它会破坏我的程序。

感谢任何帮助。谢谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    它是 User 和 FriendRequest 模型之间的中介模型。

    通过使用 BUILD 方法,您可以创建一个新的 ActiveRelationship,然后您可以创建新的 FriendRequest。

    用户 >> ActiveRelationship >> 好友请求

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 2013-08-19
      • 2013-05-25
      相关资源
      最近更新 更多