Получение URL формы вложенного идентификатора ресурса - PullRequest
0 голосов
/ 12 февраля 2019


Я сделал вложенные ресурсы (как показано ниже).Находясь в представлении coffee_profile # show, создайте специальный рецепт для этого конкретного профиля по ссылке (/coffee_profiles/:coffee_profile_id/recipes/new(.:format)).

resources :coffee_profiles do 
  resources :recipes, only: [:new, :create, :show]
end

Я хотел пойматьcoffee_profile_id, который присутствует в URL для ссылки, к которому coffee_profile принадлежит рецепт, и скрывается в форме рецептов # new в hidden_field, чтобы просто передать его с другими параметрами при отправке.

Однако я не знаю, как получить этот идентификатор сам, hidden_field создает этот параметр, но он заполняется нулем после отправки coffee_profile_id: ''


это из recipes_controller.rb

def new
  @recipe = Recipe.new 
end 

def create
  @recipe = current_user.recipes.build(recipe_params)
  if @recipe.save
    flash[:success] = "Recipe created!"
    redirect_to root_path
  else
    flash[:error] = @recipe.errors.inspect
    render :new
  end
end


И это рецепты # new form_for:

<%= form_for(@recipe) do |f| %>
  ...
<% end %>

Любая помощь приветствуется, и дайте мне знать, если вам нужна дополнительная информация/code.

журнал консоли

1 Ответ

0 голосов
/ 12 февраля 2019

Поскольку вы используете вложенные ресурсы, каким-то образом должен присутствовать coffee_profile.

На самом деле нет необходимости хранить ваш рецепт где-нибудь, потому что ваш рецепт имеет отношения has_many и own_to.

Вам нужно изменить свою форму следующим образом:

<%= form_for([@coffee_profile, Recipe.new]) do |f| %>
    <div class="recipes_form_item">
      <%= f.label :coffee %>
      <%= f.text_field :coffee %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :quantity %>
      <%= f.number_field :quantity %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :method %>
      <%= f.text_field :method %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :water_temperature %>
      <%= f.number_field :water_temperature %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :water_amount %>
      <%= f.number_field :water_amount %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :grind %>
      <%= f.text_field :grind %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :aroma %>
      <%= f.text_field :aroma %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :aroma_points %>
      <%= f.number_field :aroma_points %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :taste %>
      <%= f.text_field :taste %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :taste_points %>
      <%= f.number_field :taste_points %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :body %>
      <%= f.text_field :body %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :body_points %>
      <%= f.number_field :body_points %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :astringency %>
      <%= f.text_field :astringency %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :astringency_points %>
      <%= f.number_field :astringency_points %>
    </div>
    <div class="recipes_form_item">
      <%= f.label :brew_time %>
      <%= f.number_field :brew_time %>
    </div>
    <div class="recipes_form_item">
      <%= f.submit :Submit %>
    </div>
  <% end %>

сейчас, внутри вашего coffee_profile_controller, добавьте ваш новый метод (или везде, где вы визуализируете форму для вашего рецепта:

@coffee_profile = CoffeeProfile.find(params[:id])

Теперь внутри вашего recipe_controller добавьте внутрь create:

@coffee_profile = CoffeeProfile.find(params[:id])
@recipe = @coffee_profile.recipes.create(recipe_params)

if @recipe.save
 redirect_to root_path
end

измените также внутри нового метода все так:

def new @coffee_profile = CoffeeProfile.find (params [: id]) @recipe = @ coffee_profile.recipe.new end

и для recipe_params убедитесь, что вы принимаете :coffee_profile_id

params.require(:recipe).permit(:id, your other values and :coffee_profile_id)

Теперь, когда вы идете в свойНа консоли вы можете сказать: @recipe = Recipe.last

, а затем @recipe.coffee_profile, что даст вам всю информацию о профиле кофе.

Привет!

...