0

First of all, I've done a fair amount of looking around, and while questions get around answers, I have a problem I think is somewhat unique. I have a list of checkboxes generated with the following code:

<% for student in Student.find(:all) %>
    <div>
    <%= check_box_tag "user[student_ids][]", student.id, current_user.students.include    (student) %>
    <%= student.name %>
    </div>
<% end %>

After clicking the 'update' button at the bottom, I need each of the checked boxes to be placed into an array. I then plan on iterating over the array and doing some work on each of the checked names. I am having a hard time, however, with the process of getting these names all into an array. I really am not sure which of the standard web actions this kind of work should be (i.e, post, get, etc.), so I don't know how to set up a route. Even if I could set up a route to a controller, how would I get the checked students into an array of Student objects?

Thanks ahead of time for your help!

4

2 に答える 2

0

あなたの質問に対する完全な答えは、たとえば、送信された配列で何をしようとしているのかなど、さまざまなことに依存します (これにより、POST、GET、PUT、または DELETE を使用する必要があるかどうかが決まります)。コードベースに関して、次のコードをコントローラーのすでに安静なルートの1つで form_for にスローすると、チェックされた名前の配列を確認できるはずです。

<%= current_user.students.include(student).each do |student| %>
    <div>
        <%= check_box_tag "student_names[]", student.name %> <%= label_tag student.name %>
    </div>
<% end %>

次に、ユーザーが送信を押すと、params ハッシュに student_names = [] が表示されます。

また、必要に応じて属性にアクセスできることを確認してください。

余談ですが、先週の Railscasts プロ エピソードをご覧ください。あなたがやろうとしていることをほぼ正確に説明しています。ただし、サブスクリプションサービスです。

于 2013-03-06T16:39:21.863 に答える
0

私は満足のいく方法で問題を解決することができませんでした。最終的に使用したコードは次のとおりです。

current_user.students.delete_all
  if(params.has_key? :user)
     params[:user][:student_ids].each do |i|
        current_user.students<<(Student.find(i))
     end
  end

私が管理している学生の数は 100 人を超えることはないので、この操作は見た目ほど悪くはありません。すでに存在するすべての関連付けを削除してから、渡されたすべてのパラメーターを循環しています。次に、渡されたパラメーター id を持つ学生オブジェクトを見つけて、それを current_user の User-Student 結合テーブルに追加します。

これが誰かの助けになることを願っています!

于 2013-04-10T22:42:19.270 に答える