【发布时间】:2017-04-26 01:34:35
【问题描述】:
我有三个实体:用户、联系人和参与度。 user 那个has_many: contacts。联系belongs_to: user。用户与联系人进行互动。我也有订婚belongs_to: contact。
在我的views/contacts/show.html.erb 中,我想显示特定联系人的页面,并让用户通过填写参与表格来注册与联系人的参与。我希望在联系人页面上创建的参与与该特定联系人相关联。
所以我显示一个联系人:
resources :contacts
resources :engagements, only: [:create, :edit, :destroy]
class ContactsController < ApplicationController
include ApplicationHelper
def show
@contact = Contact.find(params[:id])
set_current_contact @contact.id #pass the particular id to helper
end
end
在助手中定义方法:
module ApplicationHelper
def set_current_contact(contact_id)
@current_contact = Contact.find_by(id: contact_id)
end
def the_current_contact
@current_contact #create instance variable for the other helper
end
end
我想要做的关键事情是让参与控制器“知道”用户正在注册参与的联系人。即通过@contact 到EngagementsController
class EngagementsController < ApplicationController
def create
@engagement = the_current_contact.engagements.build(engagement_params)
end
end
我得到错误:
undefined method `set_current_contact' for #<EngagementsController:0x007f2c2c24f360>
第一个问题是我不明白为什么控制器不能从ApplicationHelper 访问方法?
我并不是要问两个不同的问题,但第二个问题是以这种方式使用帮助程序是否是正确的方法。我知道 HTTP 是一种无状态协议,在这种情况下,帮助程序对于传递实例变量很有用。我搜索了类似的帖子并找到了相关的Rails: Set a common instance variable across several controller actions,但虽然它推荐了帮助器作为解决方案,但它并没有特别说明如何使用帮助器。
编辑:我在EngagementsController 中添加了缺少的include ApplicationHelper。现在的错误是:
wrong number of arguments (given 0, expected 1)
Extracted source (around line #13):
end
13 def set_current_contact(contact_id)
14 @current_contact = Contact.find_by(id: contact_id)
15 end
【问题讨论】:
-
您忘记在 EngagementsController 中输入
include ApplicationHelper。即使你解决了这个问题,你的假设是正确的,它不会像你期望的那样工作:)
标签: ruby-on-rails