【发布时间】:2014-11-12 04:33:36
【问题描述】:
所以,我有一个搜索栏,所以用户(亚当)可以搜索另一个用户(鲍勃)
- 搜索栏根据名称搜索用户。 (搜索 'bob' 返回 'bob')(这发生在 users/index.html.erb 上)
- 一旦找到用户,他们的名字就会显示出来,并且搜索结果旁边会出现一个“添加关系”按钮。 (鲍勃“添加关系”)(再次在 users/index.html.erb 上弹出)
我希望“添加关系”按钮链接到一个页面:“relationships/new/bob”(relationships/new/friendname)
目前它链接到 /relationships/new?followed_id=bob
有什么想法可以让 '/relationships/new?followed_id=bob' 变成 'relationships/new/bob'?
**是否是发送不同的参数或变量以使搜索返回“bob”而不是“?followed_id=bob”的情况?
或者,是否可以将正在搜索的人的姓名参数与搜索结果一起发送,以便在按下时链接到“添加关系”按钮?
(其他相关信息,has_many 和 has_many through 关系都设置正确,所以用户 has_many 关系,to_params 也设置在 users 模型中,我不相信答案与这些方面有任何关系)
users_controller:
def index
@users = User.search(params[:search])
@followed = User.find_by(name: params[:search])
# @followed = User.find_by_name(params[:id])
end
用户/index.html.erb:
<%= form_tag users_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<ul>
<% @users.each do |user| %>
<li>
<%= user.name %>
<%= link_to "Add Relationship", new_relationship_path(followed_id: @followed), class: "btn btn-primary" %>
<%= @followed %>
</li>
<% end %>
</ul>
relationships_controller:
def new
if params[:followed_id]
# @followed = User.find_by(name: params[:followed_id])
# @followed = User.find(params[:followed_id])
# @followed = User.find_by_name(params[:id])
raise ActiveRecord::RecordNotFound if @followed.nil?
@active_relationship = current_user.active_relationships.new(followed: @followed)
else
flash[:danger] = "Relationship required"
end
rescue ActiveRecord::RecordNotFound
render 'public/404', status: :not_found
end
【问题讨论】:
标签: ruby-on-rails variables routes url-routing params