[英]Rails 4 - simple form: how do I populate a form field based on the link used to access the form?
我在Rails 4应用程序中有针对项目和兴趣的模型。 关联是:
项目
has_many :interests
利益
belongs_to :project
belongs to: user
兴趣表的目的是让用户注册对项目的兴趣。
在我的项目展示视图中,我有两个链接来表示兴趣。 用户可以以参与者或观察者的身份表达对项目的兴趣。
以我的兴趣形式,我有两个布尔字段,分别是:participant和:observer。
我试图弄清楚如何用'true'填充相关的布尔属性,具体取决于用户单击该链接以获取表单的链接。 如果他们单击“参与此项目”,那么兴趣表中的参与者属性应设置为true。
根据我的兴趣表,我有:
<%= f.hidden_field :user_id, @current_user.id %>
<%= f.hidden_field :project_id, @project.id %>
<%= f.input :observe, as: :radio_buttons, :label => "Do you want to monitor this project?" %>
<%= f.input :participate, as: :radio_buttons, :label => "Do you want to participate in this project?" %>
有没有一种方法可以让我自动完成观察并以这种形式参与布尔值(基于用户从显示的项目中访问该表单所遵循的链接)?
兴趣路线(在我的应用中实际上称为“ eoi”:
rake routes | grep eoi
eois GET /eois(.:format) eois#index
POST /eois(.:format) eois#create
new_eoi GET /eois/new(.:format) eois#new
edit_eoi GET /eois/:id/edit(.:format) eois#edit
eoi GET /eois/:id(.:format) eois#show
PATCH /eois/:id(.:format) eois#update
PUT /eois/:id(.:format) eois#update
DELETE /eois/:id(.:format) eois#destroy
在项目展示视图中,我具有以下链接,以注册参与或监视项目的兴趣:
<%= link_to 'Participate', new_eoi_path(@eoi) %>
<%= link_to 'Monitor', new_eoi_path(@eoi) %>
您可以传递它是观察者还是参与表单的查询字符串。
将转到此表单的路由助手更改为
new_eoi_path(observe: true)
要么
new_eoi_path(participate: true)
然后在新视图中将输入更改为
<%= f.input :observe, checked: params[:observe],as: :radio_buttons, :label => "Do you want to monitor this project?" %>
<%= f.input :participate, checked: params[:participate], as: :radio_buttons, :label => "Do you want to participate in this project?" %>
编辑
如何将此用作输入?
<%= f.radio_button :observe, true, :checked => params[:observe] %>
<%= f.radio_button :participate, true, :checked => params[:participate] %>
将此添加到您的视图
<%= link_to 'Participate', new_task_path(@eoi, participate: true) %>
<%= link_to 'Monitor', new_task_path(@eoi, observe: true) %>
在您的控制器中
def new
@task = Task.new
@participate = params[:participate] # will be nil if observe link was clicked
@observe = params[:observe]
end
最后在表单中,将checked
的值设置为基于@observe
或@participate
的值
<%= f.input :observe, checked: @observe, as: :radio_buttons, :label => "Do you want to monitor this project?" %>
<%= f.input :participate, checked: @participate, as: :radio_buttons, :label => "Do you want to participate in this project?" %>
额外
如果用户单击observe
链接,您将要检查observe
并uncheck
participate
。 为此,请将您的new
操作替换为
def new
@task = Task.new
@participate = params[:participate] || false
@observe = params[:observe] || false
end
这样,如果用户单击observe
链接,则将值yes
设置为observe
而将no
设置为participate
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.