我有以下型号:
User
--------
has_many :publications, through: :publication_users
Publication
--------
has_many :users, through: :publication_users
PublicationUser
--------
belongs_to :user
belongs_to :publication
我希望能够拨打Publication.first.users.first.role
,但我收到undefined method 'role' for #<User:0x007fc03f0ff080>
错误。如何访问此关系属性?
我还希望能够设置每个用户的角色。例如:
def make_creator_admin
# have some way of setting the role here. Right now I can't :(
self.users << self.owner
end
我设法找到的是关于accepts_nested_attributes_for
的大量帖子,但似乎更具体地提交了提交内容。有任何想法如何有效地管理这个?
总而言之,我希望能够完成以下两项:
1。访问与出版物相关联的用户的角色
2。设置该用户的角色
答案 0 :(得分:0)
如果import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class ForLoopPerformanceTest {
private static List<Integer> list = new ArrayList<>();
private static long startTime;
private static long endTime;
static {
for (int i = 0; i < 1_00_00_000; i++) {
list.add(i);
}
}
@SuppressWarnings("unused")
public static void main(String[] args) {
// Type 1
startTime = Calendar.getInstance().getTimeInMillis();
for (Integer i : list) {
//
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " + (endTime - startTime) + " ms");
// Type 2
startTime = Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < list.size(); j++) {
//
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");
// Type 3
startTime = Calendar.getInstance().getTimeInMillis();
int size = list.size();
for (int j = 0; j < size; j++) {
// System.out.println(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println(
"Using [int size = list.size(); int j = 0; j < size ; j++] :: " + (endTime - startTime) + " ms");
// Type 4
startTime = Calendar.getInstance().getTimeInMillis();
for (int j = list.size(); j > size; j--) {
// System.out.println(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");
}
}
是role
表中的属性,为什么要拨打publication_users
?为什么不Publication.first.users.first.role
在您的模型中加入Publication.first.publication_users.first.role
:
has_many :publication_users
此外,要在关联中设置用户的角色,请定位关联,而不是用户,如上所述