我是Rails的新手(这里是Stackoverflow),我正在做我的第一个应用程序。应用程序允许在另一个视图中创建旅行和管理他们的铭文,使用的路线是:旅行/:旅行_id/铭文等。为此,我定义了两种模式:旅行和铭文:
class Excursion < ActiveRecord::Base
has_many :inscriptions
validates :name, presence: true, length: { minimum: 5 }
validates :busSpots, presence: true, length: { minimum: 0 }
validates :lunchSpots, presence: true, length: { minimum: 0 }
end
class Inscription < ActiveRecord::Base
belongs_to :excursion, :autosave => true
validates :name, presence: true, length: { minimum: 5 }
validates :phoneNumber, presence: true, length: { is: 9 }
validates :email, presence: true #Afegir regexp per a email validation.
validates :busSpots, presence: true, length: { minimum: 0 }
validates :lunchSpots, presence: true, length: { minimum: 0 }
end之后,我以这样的方式定义了我的routes.rb:
resources :excursions do
resources :inscriptions
end这是我的index.html.erb短途旅行视图:
<% @excursions.each do |excursion| %>
<tr>
<td><%= excursion.name %></td>
<td><%= excursion.busSpots %></td>
<td><%= excursion.lunchSpots %></td>
<td><%= excursion.active %></td>
<td><%= link_to 'Show details', excursion_path(excursion) %></td>
<td><%= link_to 'Edit excursion', edit_excursion_path(excursion) %></td>
<td><%= link_to 'Delete excursion', excursion_path(excursion),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
<td><%= link_to 'Show inscriptions', excursion_inscriptions_path(:excursion_id => excursion.id) %></td>
<td><%= link_to 'Do an inscription', new_excursion_inscription_path(:excursion_id => excursion.id) %></td>
</tr>
<% end %>一切正常,但我怀疑我的铭文控制器没有接收到:excursion_id。当我试图保存题词时,我使用了create方法:
def create
@excursion = Excursion.find(params[:excursion_id])
@inscription = Inscription.new(inscription_params)
@inscription.excursion_id = @excursion.id
if @inscription.save
redirect_to @inscription
else
render 'new'
end
end当我试图保存一个题词时,数据会被保存,但是excursion_id外键在数据库中是空的。所以我的问题是:我做错了什么?在题名控制器中使用excursion.id的正确方法是什么?
谢谢。
编辑:我刚刚意识到铭文表有2列: excursions_id和excursion_id。第一个是由模型belongs_to标签Rails创建的。第二列由外键声明创建。为什么会发生这种情况?在ActiveRecord中手动定义外键正确吗?
EDIT2并解决了:最后,这个问题与创建表有关。我在铭文表上做了两个外键。对于可能的未来用户,我已经这样创建了我的题字表:
class CreateInscriptions < ActiveRecord::Migration
def change
create_table :inscriptions do |t|
t.belongs_to :excursion, index:true, foreign_key: true
t.string :name
t.integer :phoneNumber
t.string :email
t.integer :busSpots
t.integer :lunchSpots
t.timestamps null: false
end
#THIS LINE WAS NOT NECESSARY -> add_reference :inscriptions, :excursion, index: true, foreign_key: true
end
end感谢安德鲁亨德利和张弗雷德里克的帮助和耐心。
发布于 2016-02-21 20:37:10
这可能是因为很强的参数。您需要将excursion_id添加到允许的参数中。
def excursion_params
params.require(:excursion).permit(:name, :busStops, :lunchStops, :active, inscriptions_attributes: :excursion_id)
end https://stackoverflow.com/questions/35541582
复制相似问题