在我的表单中,用户必须为他的帖子选择一个类别。
<div class="field form-group">
<%= f.text_field :category, class: "form-control" %>
</div>
(目前我使用的是文本输入而不是下拉列表)
帖子属于类别
@post = @category.posts.build(post_params)
但是我不明白如何从该字段中获取类别值。我尝试将一个数字传递给 find_by id,并将字符串传递给 find_by 名称。
@category = Category.find(params[:category]) #returns no Categoy with nil id
@category = Category.find_by(name: params[:category]) #returns no method error
任何帮助,将不胜感激
编辑:
表格代码
<%= form_for [@company, @post], :html => { :class => "form-posts"} do |f| %>
<div class="field form-group">
<div class="input-group input-group-lg">
<span class="input-group-addon">$</span>
<%= f.text_field :text, class: "form-control", placeholder: "text", required: true %>
</div>
</div>
<div class="field form-group">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-calendar"></i>
</span>
<%= f.text_field :date,
class: "form-control",
value: @today,
data: {behaviour: "datepicker"},
required: true %>
</div>
</div>
<div class="field form-group">
<%= f.text_field :comment, class: "form-control", placeholder: "Comment (optional)" %>
</div>
<div class="field form-group">
<%= f.text_field :category, class: "form-control" %>
</div>
<div class="actions"><%= f.submit 'Add', class: "btn btn-lg btn-primary" %></div>
<% end %>
编辑 2
控制器:
形式:
<%= f.text_field :category, class: "form-control" %>
定义创建
@company = current_user.companies.find(params[:company_id])
@category = @company.categories(params[:category])
@post = @category.posts.build(post_params)
调试器:
{"utf8"=>"✓", "authenticity_token"=>"...", "transaction"=>{"text"=>"lalala", "date"=>"11.11.2013", "comment"=>"", "category"=>"5"}, "commit"=>"Add post", "action"=>"create", "controller"=>"posts", "company_id"=>"2"}
undefined method `transactions'