0
我正在創建一個twitter副本(只是爲了學習Rails)。我有一個用戶頁面,列出所有用戶。在用戶名旁邊,我想創建一個按鈕,如果您沒有關注此用戶,請點擊「關注」,如果您不關注,請點擊「取消關注」。Ruby on Rails:創建一個按鈕,如果在db中存在一行
我已經在PHP中完成了它,我認爲我可以在Rails中做類似的事情,但我不知道如何。
followBtn.php - 包含在每個用戶之後。
$subsTable = new Table('Sub');
if($user != $currentUser) {
$follows = $subsTable->checkFollow($currentUserID, $userID);
if($follows) {
echo "<form action='src/php/main.php' autocomplete='on' method='post'>";
echo "<input type='hidden' name='page' value='unfollow'>";
echo "<input type='hidden' name='followID' value='$userID'>";
echo "<input type='submit' value='Unfollow' id='unfollowBtn'>";
echo "</form>";
}
if(!$follows) {
echo "<form action='src/php/main.php' autocomplete='on' method='post'>";
echo "<input type='hidden' name='page' value='follow'>";
echo "<input type='hidden' name='followID' value='$userID'>";
echo "<input type='submit' value='Follow' id='followBtn'>";
echo "</form>";
}
}
Table.php
public function checkFollow($user, $follower) {
$table = (string)self::$table;
$query = "
SELECT
*
FROM
$table
WHERE
$table.userID = '$user'
AND
$table.followID = '$follower'
;";
$database = Database::getInstance();
$result = $database->fetch_assoc($query);
return $result;
}
這是我的Rails代碼到目前爲止,我已經得到了。我知道這不起作用,但也許並不是那麼錯。
index.html.erb
<h2>All users</h2>
<table>
<tr>
<th>Username</th>
<th>Email</th>
</tr>
<% @user.each do |u| %>
<tr>
<td><%= u.username %></td>
<td><%= u.email %></td>
<% if(u.username != @current_user.username) %>
<% if @following %>
<% @temp_user = u %>
<%= form_for(:subscription, :url => { :controller => "subscriptions", :action => "unsubscribe" }) do |s| %>
<%= s.hidden_field(:userID, :value => @current_user.id) %>
<%= s.hidden_field(:followingID, :value => u.id) %>
<td><%= s.submit "Unsubscribe" %></td>
<% end %>
<% else %>
<%= form_for(:subscription, :url => { :controller => "subscriptions", :action => "subscribe" }) do |s| %>
<%= s.hidden_field(:userID, :value => @current_user.id) %>
<%= s.hidden_field(:followingID, :value => u.id) %>
<td><%= s.submit "Subscribe" %></td>
<% end %>
<% end %>
<% end %>
</tr>
<% end %>
</table>
user_controller.rb
class UsersController < ApplicationController
before_filter :save_login_state, :only => [:new, :create]
def index
@user = User.all
@current_user = User.find session[:user_id]
@following = true if Subscriptions.find_by_sql("SELECT * FROM subscriptions WHERE userID = '{@current_user.id}' AND followingID = '{@temp_user.id}';")
end
end
錯誤
NameError in UsersController#index
uninitialized constant UsersController::Subscriptions
你看到了什麼錯誤? – shishirmk 2013-04-26 18:45:01
添加了該錯誤。 @shishirmk – Alexander 2013-04-26 19:05:49