【问题标题】:rails - confused about routing and paramsrails - 对路由和参数感到困惑
【发布时间】:2011-05-16 21:07:21
【问题描述】:

我有两个模型,组和用户

用户 belongs_to 组和 组 has_many 用户

在我的组/show.html.erb 中,我有用户注册表单

<h1>Create user</h1>

<%= form_for @user do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </div>
  <div class="field">
    <%= f.label :password_confirmation, "Confirmation" %><br />
    <%= f.password_field :password_confirmation %>
  </div>
  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>    

为了获得组和用户之间的关系,我在用户控制器中有一个 create 方法,如下所示

def create
    @group = Group.find(params[:group][:id])    
    @user = @group.users.build(params[:user])
    if @user.save
      flash[:success] = "You have created a new user"
      redirect_to group_path
    else
      @title = "Create user"
      render 'new'
    end
end

我也试过: @group = Group.find(params[:id])

@group = Group.find(params[:group_id])

但我仍然收到错误

基本上我想在 group/show.html.erb 中创建新用户并将该用户与创建用户的组相关联。例如,如果用户是在 groups/3 中创建的,我如何在 Users 控制器中设置我的创建方法以确保这种关系成立?

总的来说,我一直在关注http://ruby.railstutorial.org/chapters/user-microposts#sec:creating_microposts 上的 Hartl Rails 教程,并遵循表单和创建方法的方法。但是我不确定如何将 groups/3 的参数放入 find 方法中,例如 @group = Group.find(?????)

谁能赐教,这个问题困扰我好几天了。

提前致谢

【问题讨论】:

  • 我感觉我可能需要在表单中使用 hidden_​​field_tag 来传递 group.id 但不知道该怎么做

标签: ruby-on-rails-3 params


【解决方案1】:

提交表单后,它会将您带到 users#create。此路线没有 group_id 段。

要在此处传递 group_id,您需要将其存储在表单的隐藏字段中。

【讨论】:

  • 我可以这样做吗: @group.id %>,然后在我的 users#create 中这样做 @group = Group.find(params[:group_id ])?
  • 这已经解决了,我解决了 ,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 1970-01-01
  • 2017-02-28
  • 2015-09-05
  • 2014-11-19
  • 2011-12-30
相关资源
最近更新 更多