Rails - 将视图中的值输出到控制器中

时间:2013-11-11 12:01:11

标签: ruby-on-rails ruby-on-rails-4

在我的表单中,用户必须为其帖子选择一个类别。

  <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" %>

def create

@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'

2 个答案:

答案 0 :(得分:4)

查看开发日志。

可能会有类似params[:post][:category]

的内容

答案 1 :(得分:2)

获取您的类别:

params[:post][:category]