Я хотел бы назначить event_option_id для регистрации. Я могу легко сделать это на вид, добавив его в форму:Rails присваивает идентификатор в модели
<%= f.text_field :event_option_id, value: @event_option.id %>
Я хотел бы сделать это в модели не на виду. Для безопасности я делаю то же самое для регистрационной цены. Установка цены с модели работает, но делать то же самое для event_option_id нет.
Регистрация Модель:
class Registration < ActiveRecord::Base
belongs_to :event_option
belongs_to :order_item
belongs_to :order
before_save :set_event_options
def order_present
if order.nil?
errors.add(:order, "is not a valid order.")
end
end
def registration_price
self[:price] = event_option.price
end
def event_option_id
self.event_option_id = event_option
end
private
def set_event_options
self[:price] = registration_price
self.event_option_id = event_option_id
end
end
EventOptions модель:
class EventOption < ActiveRecord::Base
belongs_to :event
has_many :registrations
end
Создать метод в контроллере Регистраций:
def create
@event_option = EventOption.find(params[:id])
@order = current_order
@registration = @order.registrations.build(registration_params)
#@registration = Registration.new(registration_params)
@order_id = current_order.id
respond_to do |format|
if @registration.save
format.html { redirect_to @registration, notice: 'Registration was successfully created.' }
format.json { render :show, status: :created, location: @registration }
format.js {}
@order.save
session[:order_id] = @order.id
else
format.html { render :new }
format.json { render json: @registration.errors, status: :unprocessable_entity }
end
end
Ошибка в журнале:
Started POST "/registrations" for 127.0.0.1 at 2016-01-04 21:16:06 -0500
Processing by RegistrationsController#create as JS
Parameters: {"utf8"=>"âo"", "registration"=>{"name"=>"saasas", "lastname"=>"asas"}, "commit"=>"Create Registration"}
EventOption Load (0.0ms) SELECT "event_options".* FROM "event_options" WHERE "event_options"."id" = ? LIMIT 1 [["id", nil]]
Completed 404 Not Found in 8ms (ActiveRecord: 0.0ms)
ActiveRecord::RecordNotFound (Couldn't find EventOption with 'id'=):
app/controllers/registrations_controller.rb:27:in `create'
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (44.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (1.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (48.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.0ms)
Rendered C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (105.0ms)
Я читаю эту часть документации рельсов: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html, , но до сих пор не могу понять, что происходит.
Обновление:
Маршруты:
Rails.application.routes.draw do
resource :cart, only: [:show]
resources :orders
resources :order_items
resources :registrations
resources :event_options
resources :events
resources :charges
root 'events#index'
Регистрационная форма - внутри event_option show.html.erb:
<%= form_for(@registration, remote: true) do |f| %>
<% if @registration.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@registration.errors.count, "error") %> prohibited this registration from being saved:</h2>
<ul>
<% @registration.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :lastname %><br>
<%= f.text_field :lastname %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Можете ли вы разместить больше своих журналов? И какой маршрут вы бьете? Является ли регистрация ребенком event_option? Почтовые маршруты, больше ваших журналов (включая параметры), и было бы замечательно видеть форму в представлении. – Swards
Я обновил сообщение с помощью журнала и маршрутов. Регистрация - это ребенок event_option, но я не вложен маршруты. – Asan
Нест маршрут, чтобы вы получили 'event_option_id' таким образом, если вы не хотите отправлять его через представление. – Swards