Rails:从数据库中检索模型ID

时间:2013-04-12 01:42:12

标签: ruby-on-rails

我正在尝试检索名为“gnib”的模型的id并将其以隐藏字段中的形式提交,以便用户在单击附加到每个gnib的提交按钮时有效地重新发布“gnib” 。但是当我点击按钮时出现错误:

ActiveRecord::Recordnotfound in Sharescontroller#create
Couldn't find Gnib with id= 

如果有人能帮我解决这个问题,我真的很感激。

Gnib模型

attr_accessible :title, :image, :content 
mount_uploader :image, ImagesUploader
belongs_to :user
validates :content, presence: true, length: { maximum: 80 }  
validates :user_id, presence: true
default_scope order: 'gnibs.created_at DESC'
has_many :reverse_shares, foreign_key: "regnib_id", class_name: "Share", dependent:     :destroy
has_many :regnibbers, through: :reverse_shares

在我的用户模型中,我有:

用户模型

 has_many :gnibs, dependent: :destroy
 has_many :shares, foreign_key: "regnibber_id", dependent: :destroy
 has_many :regnibs, through: :shares

我使用名为“Share”的连接模型来促进重新发布或“regnib”功能。

分享模式

attr_accessible :regnib_id
belongs_to :regnibber, class_name: "User"
belongs_to :regnib, class_name: "Gnib"
validates :regnibber_id, presence: true
validates :regnib_id, presence: true

共享控制器中,我有:

 def create
 @gnib = Gnib.find(params[:share][:regnib_id])
 current_user.regnib!(@gnib)
 redirect_to @gnib
 end

gnib控制器中,我有:

 def create
 @gnib = current_user.gnibs.build(params[:gnib])
 end

在show function下的用户控制器中我有:

 @gnib = current_user.gnibs.build(params[:gnib]) if signed_in?

用于呈现 gnibs 部分位于用户展示页面中,如下所示:

<li>
 <span class="Title"><%= gnib.title %></span>
 <span class="Image"><%= image_tag gnib.image_url(:thumb) %></span>
 <span class="content"><%= gnib.content %></span>
 <span class="timestamp">
 Posted <%= time_ago_in_words(gnib.created_at) %> ago.
 </span>
 <%= render 'regnib_form' %>
</li>

regnib 表单的部分是:

<% unless current_user?(@user) %>
<div id="regnib_form">
<% if current_user.regnibbing?(@gnib) %>
<% else %>
<%= form_for(current_user.shares.build(regnib_id: @gnib.id)) do |f| %>
<div><%= f.hidden_field :regnib_id %></div>
<%= f.submit "Regnib", class: "btn btn-large btn-primary" %>
<% end %>
<h4> Regnibs <%= @gnib.regnibbers.count %></h4>
<% end %>
</div>
<% end %>

1 个答案:

答案 0 :(得分:0)

<div>
  <%= f.hidden_field :regnib_id %>
</div>

应该是:

<div>
  <%= f.hidden_field :regnib_id , :value=> @gnib.id %>
</div>