我刚刚完成了 Ruby on Rails 3 教程。最后一章相当复杂。整本书的教程基本上创建了一个用户可以发布微博的网站。此外,每个用户都可以关注任何其他用户,然后以下用户的微博将显示在原始用户的微博提要中。
我的问题与为什么RelationshipsController 中的create 操作的params 变量包含一个二维数组有关。
这是代码。
用户
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
has_many :microposts, dependent: :destroy
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship", dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
end
微博
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
end
关系
class Relationship < ActiveRecord::Base
attr_accessible :followed_id
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
end
我认为这是创建二维参数变量的代码(但为什么?)
<%= form_for(current_user.relationships.build(followed_id: @user.id), remote: true) do
|f| %>
<div><%= f.hidden_field :followed_id %></div>
<%= f.submit "Follow", class: "btn btn-large btn-primary" %>
<% end %>
关系控制器
class RelationshipsController < ApplicationController
def create
@user = User.find(params[:relationship][:followed_id])
current_user.follow!(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
end
所以也许我只是回答了我自己的问题,但我从未见过 params 变量的二维数组。有人可以对此有所了解吗?
哦,也许我也应该发布我的 routes.rb 文件:
SampleApp::Application.routes.draw do
resources :users do
member do
get :following, :followers
end
end
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
root to: 'static_pages#home'
end
谢谢,迈克