1

I have an search form, for my Search model. My problem is that i only want to display the value of the form if @search is present. I wrote this code:

 <%= f.text_field :keyword, :value => @search.keyword if @search.present? %>

My problem is that when @search is not present the whole form is not displayed! I only want that the value is not displayed in this case!

UPDATE UPDATE:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

I wrote an little helper:

def value(link)
 if @search.present?
  value: @search.link
 end
end

And in my form:

<%= f.text_field :keyword, value(keyword) %> 

But why do i get this error:

s_helper.rb:4: syntax error, unexpected ':', expecting keyword_end value: @search.link
4

4 回答 4

2

如果我理解你,如果没有@search,你仍然希望出现空输入。如果是这样,这应该做你想要的:

  <%= f.text_field :keyword, :value => @search.try(:keyword) %>

有关 try 方法的信息,请参阅本文 - http://everydayrails.com/2011/04/28/rails-try-method.html

于 2013-09-14T08:32:06.577 回答
0

尝试这个

<%= f.text_field :keyword, :value => @search.keyword %> <% if @search.present? %>
于 2013-09-14T08:16:16.167 回答
0

我猜你有这样的东西。

<%= form_for @search do |f| %>

将其更改为

<%= form_for (@search || Search.new) do |f| %>

@search...而不是从表单字段中删除所有内容。

于 2013-09-14T08:24:15.677 回答
0

您可以使用present?通过 Rails API 提供的方法,

<% if @search.present? %>
  <%= f.text_field :keyword, :value => @search.keyword %>
<% end %>

请参阅此处了解更多信息。

于 2013-09-14T08:25:36.487 回答