【问题标题】:rails getting value from view to conroller轨道从视图到控制器获取价值
【发布时间】:2013-07-17 04:05:48
【问题描述】:

从表单向控制器获取值时遇到问题。我正在使用 Rails 4.0。

我的视图看起来像这样 (new.html.erb)

<h1> POST A NEW LISTING </h>

    <% if current_user.nil? %>
        <h2>You must be logged in to view this page </h2>
    <% else %>
        <%= form_for [@user, @listing] do |f| %>
      <%= f.label :title, 'Title' %> <br />
      <%= f.text_field :title %>

      <%= f.label :general_info, 'General Information' %> <br />
      <%= f.text_area :general_info %>

      <%= f.label :included, 'Included' %> <br />
      <%= f.text_field :included %>

       <%= f.label :length, 'Length' %> <br />
      <%= f.text_field :length %>

      <%= f.label :price, 'Price' %> <br />
      <%= f.text_field :price %>

      <%= fields_for @tagging do |u| %>
        <%= u.label :tag, 'Tag' %> <br />
        <%= u.text_field :tag %>
      <% end %>

      <%= f.submit "submit" %>
    <% end %>

    <% end %>

我正在尝试添加标签。我有 2 个模型来处理标签:

模型 -> tag.rb

class Tag < ActiveRecord::Base
    has_many :taggings
    has_many :listings, through: :taggings
end

模型 -> tagging.rb

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :listing
end

tags 跟踪标签名称本身,而 taggings 跟踪与列表的连接。

当用户提交表单时,他们将输入一个字符串标签,例如:“exampletag”。然后我需要搜索我的标签模型以获取该特定标签的 tag_id。如果存在,我需要将 tag_id 和 listing_id 放入标记中。目前我的listing_id 正确,但即使从表单访问:tag 符号也有问题。

这是我目前所拥有的。并不是说当前 :tag_id 是硬编码的,因为我无法让 @current_tag 返回我需要的信息。

listings_conroller.rb #create

  def create
    @user = User.find(current_user.id)
    @listing = @user.listings.build(listing_params)     
    #save before we get the listing ID

    if @listing.save

        @current_tag = Tag.where(:name => params[:tag])
          @taggings = Tagging.new(:tag_id => 1, :listing_id => @listing.id)

        if @taggings.save
            flash[:success] = "Success"
            redirect_to root_path 
        else
          render :action => 'new'
        end
    else
     render :action => 'new'
    end

  end

我认为 @current_tag = Tag.where(:name => params[:tag]) 会返回正确的列表,但是当我提交具有数据库中名称的表单时,它似乎返回 null。

【问题讨论】:

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


    【解决方案1】:

    知道了!

    由于标签嵌套在标签下,我需要将参数访问为:

    params[:tagging][:tag]
    

    而不是 params[:tag]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      相关资源
      最近更新 更多