在表单的参数前面添加一个字符串

时间:2013-09-07 00:15:29

标签: ruby-on-rails ruby ruby-on-rails-3

我想在表单上的参数表面前添加一个字符串,以便当用户在表单上提交内容时,它会发布到外部API,我的客户端可以登录到freshdesk.com,而不是说{ {1}},它会说BOB

Hello from BOB

我在我看来试过这个:

Hello from [:username]

但它不起作用。我也尝试使用一个值:

= f.text_field "Hello From, #{:username}" 

但这也不起作用。这是我的表格:

= f.text_field :subject, value: "Hello From, #{:username}"

这是我的控制器:

= form_for(:contacts, url: contacts_path) do |f|
  = f.error_messages
  = f.label :subject, "Name"
  %span{style: 'color: red'} *
  = f.text_field :subject, class: "text_field width_100_percent"
  %br
  %br    
  = f.label "Email"
  %span{style: 'color: red'} *
  %br    
  = f.email_field :email, class: "text_field width_100_percent"
  %br
  %br
  = f.label "Question(s), and/or feedback"
  %span{style: 'color: red'} *
  %br
  = f.text_area :description, class: "text_field width_100_percent", style: 'height: 100px;'
  %br
  %br
  = f.submit "Submit", class: 'btn btn-warning'

这是我的模特

def new
  @contacts = Form.new
end

def create
  @contacts = Form.new(params[:contacts])
  @contacts.post_tickets(params[:contacts])
  if @contacts.valid?
    flash[:success] = "Message sent! Thank you for conacting us."
    redirect_to new_contact_path
  else
    flash[:alert] = "Please fill in the required fields"
    render action: 'new'
  end
end

2 个答案:

答案 0 :(得分:2)

你的观点应该有简单的字段,没有魔法。我们将使用Form类来完成复杂的操作。

= f.text_field :subject

对post_tickets的方法调用不需要接收params,因为Form对象已经使用params值进行了初始化。另外,我认为你不应该发票,除非该对象有效,对吧?

def create
  @contacts = Form.new(params[:contacts])
  if @contacts.valid?
    @contacts.post_tickets
    flash[:success] = "Message sent! Thank you for contacting us."
    redirect_to new_contact_path
  else
    flash[:alert] = "Please fill in the required fields"
    render action: 'new'
  end
end

您的表单模型应负责修改:subject参数以包含前缀:

class Form
  # Some code omitted

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def post_tickets
    client.post_tickets({
      :whatever_fields => whatever_attribute, 
      :username => username, 
      :subject => "Hello from, #{subject}", 
      :email => email, 
      :description => description
    })
  end

end

这样,Form对象具有用户提交的正确值,但是您已经覆盖了已发布的主题,因此它将返回您想要的组合字符串,并显示“Hello from ...”

在post_tickets中,通过已初始化Form对象的属性直接引用要发送的参数。在subject的情况下,您将发送组合值。

请注意,我已重写您的初始化以使用更经典的属性设置方法。

思考,问题?

答案 1 :(得分:1)

您应该在您的模型中通过在值que表单发送给您之前添加子字符串来执行此操作。这似乎是业务逻辑,它不应该在视图中。

def post_tickets(params)
   client.username = "Hello From, " + client.username
   client.post_tickets(params)
end