我有3个型号。连接这些2的用户(电子邮件,姓名等),爱好(姓名)和兴趣(user_id,hobby_id)。在/兴趣中,我有一张当前登录用户的爱好表。如何创建一个按钮来切换(创建和销毁)用户和业余爱好之间的连接?
这是我的尝试:
<p>UID: <%= @interest.user_id %></p>
<p>HID: <%= @interest.hobby_id %></p>
然后在new.html.erb
getTransaction(id: number): Observable<Transaction>{
return this.getTransactions().pipe(
map(txs => txs.find(txn => txn.id === id))
);
}
但当然这不起作用。
我想Rails每次提出请求时都会创建@interest的新实例,但我怎样才能克服这个问题呢?
答案 0 :(得分:1)
如果我理解你的问题,你想要链接到一个新兴趣,如果用户没有,并且你想在用户确实感兴趣时链接到销毁路径。
因此,在您的控制器中,您可以使用@interest = @user.interests.find_or_initialize_by(hobby_id: hobby.id)
来获取用户兴趣或初始化新用户
# check if `@interest` is a db record
<% if @interest.persisted? %>
<%= link_to 'Destroy', interest_path, method: :delete, class "..." %>
<% else %>
<%= link_to 'Create', new_interest_path, class "..." %>
<% end %>
然后在您的视图中,检测您的用户是否有兴趣,或者我们是否初始化了一个新用户。然后显示相应的链接
users/:user_id/hobbies/:hobby_id/interests
编辑:
如果您想通过一次单击创建兴趣按钮,则需要提供操作中所需的所有参数。有几种方法可以做到这一点。你可以通过几种方式实现这一目标
在这里使用一个宁静的路线可能相当冗长,因为你有三层嵌套。使用看起来像
的路线 link_to user_hobby_interests_path([@user.id, hobby.id]), method: :post
然后,您可以向此路线提交链接(或构建表单)
/interests
或者如果您想保留form_for @interest do |f|
hidden_field_tag 'interest[user_id]', @user.id
hidden_field_tag 'interest[hobby_id]', hobby.id
submit_tag 'Create'
end
路线,则需要构建包含必要参数的表单
{{1}}