我正在尝试在Rails中创建一个带帮助器的表单,但我的所有字段都没有创建。我有一个帮助,我包括在我的视图中(我将它们都包括在内)。但由于我是铁杆新手,我甚至不确定我是以正确的方式做到这一点。
当我像这样写它时,它首先看起来像是有效的,因为按钮被创建但是当我点击它时没有传递任何值并且在DB中创建一个空行(id和timestamp除外)。
users_helper.rb
module UsersHelper
def sub_button(u)
@current_user = User.find session[:user_id]
@temp_user = u
@sub = Subscription.where("userID = ? AND followingID = ?", @current_user.id, @temp_user.id)
if @sub.blank?
@following = false
else
@following = true
end
if(u.username != @current_user.username)
if @following
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)
s.submit "Unfollow"
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)
s.submit "Follow"
end
end
end
end
end
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>
<td><%= sub_button(u) %></td>
</tr>
<% end %>
</table>
所以我在想,如果我错过了创造领域的东西......任何线索?
答案 0 :(得分:2)
我不确定,但我认为这应该是如何组织的:
module UserHelper
def sub_button u
@current_user = User.find session[:user_id]
@temp_user = u
@sub = Subscription.where("userID = ? AND followingID = ?", @current_user.id, @temp_user.id)
if @sub.blank?
@following = false
else
@following = true
end
if(u.username != @current_user.username)
if @following
render partial: 'shared/unfollow', locals: { current_user: @current_user, u: u }
else
render partial: 'shared/follow', locals: { current_user: @current_user, u: u }
end
end
end
视图/共享/ _unfollow.html.erb
<%= 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) %>
<%= s.submit "Unfollow" %>
<% end %>
视图/共享/ _follow.html.erb
<%= 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) %>
<%= s.submit "Follow" %>
<% end %>