0
从窗体获取值到控制器时出现问题。我正在使用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
标签跟踪标签名称本身,而引用的Tagging跟踪与列表的连接。
当用户提交表单时,他们将输入字符串标签,如“exampletag”。然后我需要搜索我的标签模型以获取特定标签的tag_id。如果存在,我需要将tag_id和listing_id放入标记中。目前,我有正确的listing_id,但即使从表单中访问:标记符号,也有问题。
这是我到目前为止。目前还不是:tag_id是硬编码的,因为我不能获得@current_tag来返回我需要的信息。
listings_conroller.rb#创建
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(:名称=> PARAMS [:标签])将返回正确的上市,但它似乎是返回null当我用数据库中的名字提交表单。